An introduction to the YahooFinance Stocks API for retrieving simple stock information using Python

As someone who likes to invest in stocks and someone who loves to use Python, I have experimented with several tools and APIs in order to retrieve stock market data. During this pursuit, I have run into issues such as a lack of a free service, a limit on the number of transactions, the service being obsoleted or large transaction times.

However, a few services have proven to be useful and efficient despite having a monthly transaction limit. Some of the tools I have used are:

  • Polygon API
  • Python’s yfinance module
  • Google Finance API
  • Rapid API’s Yahoo Finance API
  • Rapid API’s YahooFinance Stocks API

To be fair, I did not get a chance to use the Polygon API long enough but one limitation I came across immediately was that you could not retrieve more than two weeks worth of historical stock data at a time. This fact diverted me away from the service and I am yet to revisit it.

Python’s yfinance library contains an extensive list of stock attributes that can be used but one significant drawback of the module is the long transaction time. Regardless of the type of information available within a tool, a slow service is quite frustrating to use especially if the code is being deployed as an online app which requires fast operation for it to be user-friendly.

Similar to the Polygon API, I haven’t dug deep into the various offerings from the Google Finance API but from an initial inspection, the service provided limited options when it came to stock information. Also, it did not seem to provide stock attributes it actually advertised in the documentation such as the dividend yield for a particular ticker.

In my experience, the best stock-related API’s I have across were provided by Rapid API. These are the Yahoo Finance API and the YahooFinance Stocks API, both of which are fast, free and currently active services. However, they do have a monthly transaction cap for the free service and require the creation of an API key for their usage.

Despite the Yahoo Finance API being the most comprehensive tool I have used for retrieving stock market data, today I will be discussing the YahooFinance Stocks API which is also a great service for market information but not as extensive as the former. A separate post about the Yahoo Finance API will be published in the future.

What is Rapid API?

Rapid API is one of the largest hubs for finding, using and managing APIs across various industries and applications. It is used by individuals and companies alike. Corporations could prefer to use the ‘Enterprise Hub’ service provided by them for greater functionality and support. However, it also provides a seamless experience for personal use and research.

One can search for APIs across several categories and applications in the Rapid API Hub. Three key metrics are reported under each API denoting the functionality rating, transaction latency and user approval percentage. For example, the Telesign SMS Verify API shown below has values of 9.5, 735ms and 100% for the three metrics. As you can see, the most popular APIs are the ones with the highest functionality ratings and less than a second of transaction time.

Connecting to an API is simple and requires an API key as mentioned earlier. Both connecting and managing the API is done via a dashboard in the API Playground under the user’s account.

There is also a wide array of programming languages to choose from such as Python, JavaScript, C, Ruby, R etc. Under each language there are customized options for the type of connection. For example, Python has the following connection options:

  • http.client
  • Requests
  • Unirest

Most of the APIs can be used for free up to a certain number of transactions per month. Hence, the service is good for light use but might need to be upgraded to accommodate higher traffic.

Getting started with YahooFinance Stocks API

The YahooFinance Stocks API contains data spanning 75,000 stocks across 75 exchanges. It boasts a 97% popularity score with around 1.8 seconds of latency and a 98% service level which makes the API quite reliable. Using Yahoo Finance as the underlying source of data, this service provides an endpoint that connects the user with the data as it’s available on the website. The queried data is provided in JSON format.

Pricing for the service comes in three tiers where the free version allows 250 transactions per month with one request per second, which is the option I picked. However, there are higher tier options for more demanding applications.

In order to get started with the API, search for ‘YahooFinance Stocks’ in the search bar or click under the ‘Finance’ category on the left-hand panel in the API Hub and select the API from the list shown on the first page of results.

As mentioned earlier, API playground is the dashboard interface provided by Rapid API from where APIs can be managed from one consolidated page. A snapshot of the YahooFinance Stocks API dashboard is shown below.

On the left are different categories of data that can be retrieved using the API including a search bar for looking up specific categories. Each category provides various types of stock information. For example, the Financials dropdown provides attributes such as:

  • Income statement
  • Cash flow statement
  • Balance sheet

Each of these attributes can be used as part of the API call to retrieve a whole range of detailed data. Credentials for using the API are shown in the middle panel which contains two key pieces of information – X-RapidAPI-Key (API key) and X-RapidAPI-Host (API hostname). These credentials are used within the header of the API call.

A template for implementing the API is shown on the right-hand panel. Selecting a particular programming language automatically populates the code with the required template for that language making it easy for users to get up and running quickly without having to spend a considerable amount of time figuring out the syntax.

In my case, I used Python and the resulting code template can be seen in the aforementioned snapshot which uses the requests library to fetch the API data. The main API call used to retrieve the data is requests.get() which accepts four key arguments:

  1. “GET” command: Used to indicate that data is being retrieved
  2. URL of the host website
  3. Header information: Contains the Rapid API key and hostname
  4. Parameters: Stock ticker symbol for which the data is being extracted

Once the retrieved API data is stored in the response variable, the contents can be printed using the response.text command.

Examples using Python

As discussed earlier, the API provides several categories of stock data which can be used to extract key stock attributes. For our examples, we used three main API calls:

  • stock-prices
  • stock-metadata
  • stock-statistics

In our first example, we explored the ‘stock-prices’ API call. As shown in the image below, the API call is appended to the hostname containing the API’s URL. Any other API call is initiated in the same manner.

This particular API call is used to retrieve historical stock information such as share price over a certain period of time. The key arguments that need to be specified for this call are defined in the querystring variable. The arguments are:

  • End date
  • Start date
  • Ticker symbol
  • Order of dates

Once the API data is retrieved, the response text is converted to JSON format for easier parsing. Only a part of the full API response was printed to keep the output brief. Of the attributes that were returned, the one that concerns us is the ‘results’ attribute. Shown below are the first three indexes of the results representing June 22-24. A specific index contains various attributes of the stock price for that given day such as opening price, closing price, volume, day high, day low, etc.

Some additional parsing of the data allowed us to plot the historical opening and closing prices for the Google stock from July 2020 to July 2022.

Next up is the ‘stock-metadata’ API call which was used to extract basic stock information such as price, market, time zone etc. As a result, the query string becomes much simpler and only requires the ticker symbol as an argument as shown below.

Curated below are few of the attributes contained in the metadata. More details regarding the rest of the API response can be seen in the Python notebook.

Finally, let’s take a look at the ‘stock-statistics’ API call which provides more detailed stock information such as price-to-earnings (P/E) ratio, price-to-sales (P/S) ratio, earnings per share (EPS) etc, metrics that are typically used for valuing a given stock and are known as fundamentals of the stock.

Similar to the previous function, the ‘stock-statistics’ API call only requires the ticker symbol as an argument for the query string. 

Shown below are few of the key fundamental stock statistics as extracted in the code. To provide some context, the P/E ratio is simply the stock price divided by the EPS where ‘trailing’ refers to the existing ratio and ‘forward’ refers to the forecasted ratio in the future. Price to sales ratio is the market cap of the stock divided by the previous year’s total revenue.

These were just a handful of stock metrics that the API has to offer. A more comprehensive list of attributes can be explored on the Rapid API website. For more details regarding the API calls used above including data parsing, storage and analysis, check out the code on my Github repo.

I hope that this post was helpful and provided some value to anyone looking to explore new APIs for stock market data. Let me know in the comments if you have tried any other tools for extracting stock information and if so, what some of the best ones are. Also let me know if you have tried the API described here and what other important features you have come across. Cheers!