Financial Data from Yahoo Finance with Python

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

By the end of the blog, you may be wondering how did I come across with such a great library provided by Ran Aroussi. The answer to this question is just by pure luck surfing the web. But since I found it, I thought that it would be a good idea to share this resource with all of you.

Retrieving Financial Data from Yahoo Finance
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 it is a Python dictionary which we can parse to extract the desired financial data from Yahoo Finance. For instance, let’s extract a few financial key metrics for you to see how easy and convenient is.

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

2) 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, we can also use the library 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.

Get Historical Stock Prices
Get Historical Stock Prices

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))
Retrieve Historical Market Data with Python
Retrieve Historical Market Data with Python

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

import yfinance as yf

df = 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.

Stock Prices

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

Amazon historical prices

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.

Thank you for reading! If you enjoy the blog on Python for Finance, feel free to share it in your social media channels.

2 thoughts on “Financial Data from Yahoo Finance with Python

  1. Wonderful explanation!

    Is there way to download historical “.info” ? like with pdr.get_data_yahoo for prices?
    I am interested to see how was shortPercentOfFloat over a historical period of 60 days for a respective stock.

Comments are closed.