The (Unofficial) Yahoo Finance API | by Doug Guthrie | Towards Data Science

I work in the financial services industry as a data analytics manager. My role is to support my organization in any data-related need. One project we’re working on is an internal application that relies heavily on financial data; my job was to find a way to supply the relevant data.
If you search around the internet long enough you’ll be able to find solutions that will get you there (or partially there). I played around with IEX Cloud, Quandl, and others, which are great services but just aren’t free. So, like any developer looking for a solution, I started searching StackOverflow. I frequently came across Yahoo Finance as a possible solution, even though the note below sits at the top of the search results page for yahoo-finance:
PLEASE NOTE : THIS API HAS BEEN DISCONTINUED BY YAHOO. Yahoo! Finance is a service from Yahoo! that provides financial information. It is the top financial news and research website in the United States.
It looked like people were still utilizing the service though, either by web scraping or through URLs you could only find by searching through XHR requests. I knew that I didn’t want a web scraping solution, so I began scouring the network tab in Chrome’s developer tools for anything resembling data. Luckily, I stumbled upon some.
pip install yahooquery
The package provides three different classes that enable efficient and fast retrieval of data you can view through the front-end. The main class, where most of the data can be retrieved, is the Ticker class.
Pretty easy, right? Just pass a symbol or list of symbols and you’re ready to retrieve most of the data available through Yahoo Finance. Before we go forward though, it’s important to know there are additional keyword arguments you can supply to modify certain behaviour:
asynchronous, default False, optional: When set to True, requests made to Yahoo Finance will be made asynchronously. Only necessary when using more than one symbol.
backoff_factor, default 0.3, optional: A factor, in seconds, to apply between attempts after the second try. For example, if the backoff factor is 0.1, then sleep() will sleep for [0.0s, 0.2s, 0.4s, ...] between retries
country, default United States, optional: Alter the language, region, and corsDomain that each request utilizes as a query parameter. This functionality hasn’t been thoroughly tested, but you’ll see differences when utilizing the news method. Data will be returned for that country’s specific language.
formatted, default False, optional: When formatted=True, most numerical data from the API will be returned as a dictionary:
"totalCash": {    "raw": 94051000320,    "fmt": "94.05B",    "longFmt": "94,051,000,320"}
max_workers, default 8, optional: Defines the number of workers used to make asynchronous requests. This is only relevant when asynchronous=True
proxies, default None, optional: Make each request with a proxy. Simply pass a dictionary, mapping URL schemes to the URL to the proxy. You can also configure proxies by setting the environment variables HTTP_PROXY and HTTPS_PROXY.
retry, default 5, optional: Number of times to retry a failed request.
status_forcelist, default [429, 500, 502, 503, 504], optional: A set of integer HTTP status codes that we should force a retry on.
timeout, default 5, optional: Stop waiting for a response after a given number of seconds.
user_agent, random selection, optional: A browser’s user-agent string that is sent in the headers with each request.
validate, default False, optional: Validate existence of symbols during instantiation. Invalid symbols will be dropped but you can view them through the invalid_symbols property.
verify, default True, optional: Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use.
username and password: If you subscribe to Yahoo Finance Premium, pass your username and password. You will be logged in and will now be able to access premium properties/methods. All premium properties/methods begin with p_. Disable two-factor authentication for this to work.
The Ticker class can be broken up into a few different categories: modules, options, historical pricing, and premium data.
The modules correspond (usually) to a tab or data within individual tabs from the Yahoo Finance front-end. For instance, to retrieve data from the ‘Summary’ tab, you would use the summary_detail property on the Ticker class.
Or to find data within the ‘Statistics’ tab, you would use the properties valuation_measures and key_stats.
All option expiration dates can be retrieved with a simple one-liner:
faang = Ticker('fb aapl amzn nflx goog', asynchronous=True)options = faang.option_chain
The variable options will be a pandas DataFrame. The DataFrame will contain a MultiIndex composed of the symbol, expiration date, and the option type (put or call).
This one is pretty straight-forward: retrieve historical OHLC data for a symbol or list of symbols:
faang = Ticker('fb aapl amzn nflx goog', asynchronous=True)history = faang.history()
The above code will return daily YTD data. However, additional arguments can be supplied to the method:
yahooquery.ticker.history(self, period='ytd', interval='1d', start=None, end=None)Historical pricing dataPulls historical pricing data for a given symbol(s)Parameters ---------- period: str, default ytd, optional    Length of timeinterval: str, default 1d, optional    Time between data pointsstart: str or datetime.datetime, default None, optional    Specify a starting point to pull data from.  Can be expressed as           a string with the format YYYY-MM-DD or as a datetime object end: str of datetime.datetime, default None, optional    Specify a ending point to pull data from.  Can be expressed as a         string with the format YYYY-MM-DD or as a datetime object.adj_timezone: bool, default True, optional    Specify whether or not to apply the GMT offset to the timestamp received from the API. If True, the datetimeindex will be adjusted to the specified ticker's timezone.adj_ohlc: bool, default False, optional    Calculates an adjusted open, high, low and close prices according to split and dividend informationReturns -------pandas.DataFrame    historical pricing data
Functionality is also available to retrieve data for Yahoo Finance Premium subscribers. The package utilizes Selenium, and chromedriver specifically, to login to Yahoo Finance. Once logged in, the user will be able to utilize premium methods and properties to retrieve data.
One alternative to yahooquery is yfinance. It’s a package that offers similar functionality to retrieve data from Yahoo Finance. Currently, it has nearly 2,500 stars on GitHub, the highest amount when searching for python packages that offer data retrieval from Yahoo Finance. So, why should you use yahooquery over yfinance?
Maintenance: yfinance does not seem to be maintained outside of external developers creating forks.
Opinionated: In yfinance, each property call, outside of a couple, will call the same private method, _get_fundamentals. This means that the user has to retrieve all the data possible even if they’re only interested in one thing. The flip side to this though, is that each subsequent call that utilizes that private method takes almost no time because that data is already been stored in the Ticker instance.
Source of data: yfinance retrieves the majority of data (outside of historical pricing and options) from scraping a javascript variable in each Ticker’s page. Yahooquery uses API endpoints for each property/method available to the user.
Accuracy: The income statement, balance sheet, and cash flow methods are utilizing different endpoints. The one that’s used in yahooquery retrieves more data and is accurate when looking at companies outside the U.S.
Simple: The dataframe that’s returned from retrieving historical pricing for multiple symbols is in a long format in yahooquery as opposed to a wide format for yfinance.
Configuration: Keyword arguments allow for a lot of different configurations. Also, asynchronous requests are available throughout the library, not just for historical pricing like yfinance.
Faster: See the Jupyter notebook below for different examples.
View the documentation for in-depth use of the package
yahooquery.dpguthrie.com
View the source code on GitHub
github.com
View an interactive demo hosted on Heroku
Reach out if you have questions, comments, or ways to improve the package