Financial Data from Yahoo Finance with Python

Retrieving company financials from Yahoo Finance

Jose Manu (CodingFun)
4 min readJan 20, 2021

Originally published at https://codingandfun.com on January 20, 2021.

In this post, we are going to learn about a super easy to use Python package to retrieve financial data from Yahoo Finance. We will cover the main functionalities of the yfinance library. This will lead us to retrieve both, company financial information (e.g. financial ratios), as well as historical market data. The library was created by Ran Aroussi

Photo by Pixabay on Pexels.com

Installing the Package

To be able to use the library, we will need to install it. We can follow the official documentation to do that. It is quite easy, we just need to type below code in our terminal:

pip install fix-yahoo-finance==0.1.30

Then to use the package, we need to import it in our Python script as per below:

import yfinance as yf

Getting Stock Financial Information

Retrieving financial information is also super easy. Simply pass as an argument of Ticker the ticker of the company. Below code uses Amazon as an example:

Amazon = yf.Ticker("AMZN")print(Amazon.info) #outcome {'zip': '98109-5210', 'sector': 'Consumer Cyclical', segments: North America, International, and Amazon Web Services (AWS). It sells ...'website': 'http://www.amazon.com', 'maxAge': 1, 'averageVolume': 4122014, 'priceToSalesTrailing12Months': 4.705928, 'dayLow': 3175, 'ask': 3267, 'ytdReturn': None, 'askSize': 900, 'volume': 5060028, 'fiftyTwoWeekHigh': 3552.25, 'forwardPE': 71.65964, 'fromCurrency': None, 'fiveYearAvgDividendYield': None, 'fiftyTwoWeekLow....}

The outcome of the print statement is a Python dictionary which we can parse in order to extract the desired financial data from Yahoo Finance. For instance, let’s extract a few financial key metrics.

All company information is contained under the info dictionary. Therefore, we can parse the dictionary to extract the elements that we are interested in:

Amazon = yf.Ticker("AMZN") 1) Company Sector 
print(Amazon.info['sector'])
Consumer Cyclical
2) Price Earnings Ratio
print((Amazon.info['trailingPE'])
95.41489
3) Company Beta
print((Amazon.info['beta'])
95.41489

There are so many other things available within info. We can see all of them by printing the keys of info:

print(Amazon.info.keys()) #available stock information dict_keys(['zip', 'sector', 'fullTimeEmployees', 'longBusinessSummary', 'city', 'phone', 'state', 'country', 'companyOfficers', 'website', 'maxAge', 'address1', 'industry', 'previousClose', 'regularMarketOpen', 'twoHundredDayAverage', 'trailingAnnualDividendYield', 'payoutRatio', 'volume24Hr', 'regularMarketDayHigh', 'navPrice', 'averageDailyVolume10Day', 'totalAssets', 'regularMarketPreviousClose', 'fiftyDayAverage', 'trailingAnnualDividendRate', 'open', 'toCurrency', 'averageVolume10days', 'expireDate', 'yield', 'algorithm', 'dividendRate', 'exDividendDate', 'beta', 'circulatingSupply', 'startDate', 'regularMarketDayLow', 'priceHint', 'currency', 'trailingPE', 'regularMarketVolume', 'lastMarket', 'maxSupply', 'openInterest', 'marketCap', 'volumeAllCurrencies', 'strikePrice', 'averageVolume', 'priceToSalesTrailing12Months', 'dayLow', 'ask', 'ytdReturn', 'askSize', 'volume', 'fiftyTwoWeekHigh', 'forwardPE', 'fromCurrency', 'fiveYearAvgDividendYield', 'fiftyTwoWeekLow', 'bid', 'tradeable', 'dividendYield', 'bidSize', 'dayHigh', 'exchange', 'shortName', 'longName', 'exchangeTimezoneName', 'exchangeTimezoneShortName', 'isEsgPopulated', 'gmtOffSetMilliseconds', 'quoteType', 'symbol', 'messageBoardId', 'market', 'annualHoldingsTurnover', 'enterpriseToRevenue', 'beta3Year', 'profitMargins', 'enterpriseToEbitda', '52WeekChange', 'morningStarRiskRating', 'forwardEps', 'revenueQuarterlyGrowth', 'sharesOutstanding', 'fundInceptionDate', 'annualReportExpenseRatio', 'bookValue', 'sharesShort', 'sharesPercentSharesOut', 'fundFamily', 'lastFiscalYearEnd', 'heldPercentInstitutions', 'netIncomeToCommon', 'trailingEps', 'lastDividendValue', 'SandP52WeekChange', 'priceToBook', 'heldPercentInsiders', 'nextFiscalYearEnd', 'mostRecentQuarter', 'shortRatio', 'sharesShortPreviousMonthDate', 'floatShares', 'enterpriseValue', 'threeYearAverageReturn', 'lastSplitDate', 'lastSplitFactor', 'legalType', 'lastDividendDate', 'morningStarOverallRating', 'earningsQuarterlyGrowth', 'dateShortInterest', 'pegRatio', 'lastCapGain', 'shortPercentOfFloat', 'sharesShortPriorMonth', 'impliedSharesOutstanding', 'category', 'fiveYearAverageReturn', 'regularMarketPrice', 'logo_url'])

Retrieving Historical Maket Prices:

Moving on with other options offered by the library. We can also use it in order to download historical market data.

For our example, we will get historical stock prices for Amazon covering the last few years. As shown below, it is a rather simple task to do:

Amazon = yf.Ticker("AMZN") print(Amazon.history(period="max"))

Since we have specified period = max, we get the maximum number of daily prices available for Amazon. You can also pass a lower range. The valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y and ytd.

Alternatively, we can define our own start and end dates:

import yfinance as yf
import datetime
start = datetime.datetime(2012,5,31)
end = datetime.datetime(2013,1,30)
Amazon = yf.Ticker("AMZN")
print(Amazon.history(start=start, end=end))

In addition, we can also download historical prices for more than one stock simultaneously:

import yfinance as yfdf = yf.download("AMZN MSFT", start="2019-01-01", end="2020-01-01",group_by="ticker") print(df) 
print(df.AMZN)

Above lines of code returns a Pandas DataFrame including the different price data for the requested stocks.

Then, we can then select an individual stock by printing df.AMZN to have the historical market data for Amazon:

The majority of the information covered in this post is very well explained in the blog of yfinance. I recommend you to have a look as well!

Wrapping Up

In one of my previous posts, we learned how to use Pandas in order to extract data from the financial tables available in Yahoo Finance. Combining the information in my previous post and the yfinance library that we just learn about, we have access to a wide range of financial data from Yahoo Finance for our analysis.

--

--

Jose Manu (CodingFun)

Python for Finance. Learn step by step how to automate cool financial analysis tools.