Yahoo Finance API Historical Data

Without the proper tools or resources, data users find it difficult to access historical data. However, with Yahoo Finance API, getting the data is made easy. As opposed to other APIs, Yahoo offers free access to historical data whereby one can download it free of charge. Are you wondering what I am talking about? Do not worry, let us have a glimse of the subject and you will come out equipped and educated.

Yahoo finance API is a platform that provides various financial services such as stock information, quotes, movement, price, and historical data. There are 37K stocks and a representation in 50+ countries when it comes to Yahoo Finance API. It is ranked among the largest financial data source. Being a media property, you can easily access press releases, financial data, and reports. You can access the latest financial data on its web because it is updated daily.

Accessing Yahoo Finance API

The API supports several programming languages, tools, languages, and frameworks. Some of the languages include java, python, PHP, Go, C#, C, Ruby, and JavaScript among others. Let us look briefly at some quick and easy steps to follow when accessing the API.

Creation of a free account using email, google, or GitHub

  • Sign in and scroll to the API.
  • Choose your preferred plan (either free or paid).
  • Go through the start guide for easy navigation. Choose your preferred programming language and you are ready to go.
  • Finally, copy-paste the string or code in the preferred code editor, and now you can test your API.

Why Yahoo Finance API?

Simplicity: the API layout and documentation are easy to understand. After crafting a few lines of string or code in the shortest minutes possible you can get reliable results. Set up and sign up is very easy for any user regardless of their trading experience and skill.

Accurate, reliable, and real-time data, the API has low latency, fast speed and delivers real-time data.

Offers more than the known data, apart from the main data that is common to all APIs, Yahoo Finance API has extras like market analysis, options, and fundamental data. The data includes ETFs, National currencies, Crypto Assets/markets, and Mutual Funds.

The API has Eleven Endpoints

  • Stocks trending in a certain region
  • Market summary data as per the time of the request
  • Complete asset or stock suggestions that is automatic
  • Research Insights
  • Similar stock listings
  • Charted data
  • Watch a list of the most traded/added stocks.
  • Quotes on ETFs, Stocks, Bonds, Mutual funds, national currencies, and Crypto assets that are real-time
  • Every ticker symbol has detailed info.
  • Has an option for chains data relating to each stock market segment.
  • The Historical Data has various ranges and intervals

Using Yahoo Finance API Using some Programming Languages

JavaScript (Node.js) code


varaxios = require("axios").default;
var options = {
method: 'GET',
url: 'https://rest.yahoofinanceapi.com/v11/finance/quoteSummary/AAPL',
params: {modules: 'defaultKeyStatistics,assetProfile'},
headers: {
'x-api-key': 'YOUR-PERSONAL-API-KEY'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});

Python Language


import requests
url = "https://rest.yahoofinanceapi.com/v6/finance/quote"
querystring = {"symbols":"AAPL,BTC-USD,EURUSD=X"}
headers = {
'x-api-key': "YOUR-PERSONAL-API-KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)

PHP Language


$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://rest.yahoofinanceapi.com/v7/finance/options/AAPL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-api-key: YOUR-PERSONAL-API-KEY"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Downloading Historical Datavia Yahoo Finance API

When it comes to historical data, almost everyone needs it. Yahoo Finance API comes to bridge the gap through fin library.

yahoo_fin.stock_info import get_data

Below are some terms used for the historical data download,

Interval; the duration such as “1mo, 1wk. or 1d”, translated as monthly, weekly, and daily.

get_data(ticker, start_date = None, end_date = None, index_as_date

Index-date; for true default, the records dates are indexed whereas if false they columned differently.

End-date; the date end limit you want to have the data expressed in mm/dd/yyyy.

Start date; the period or start date where the data starts.

Ticker; the ticker symbol of the stock or bond you need.

Below is a one ticker example


amazon_weekly= get_data("amzn", start_date="12/04/2009", end_date="12/04/2019", index_as_date = True, interval="1wk")
amazon_weekly

The above ticker retrieves historical data weekly and between 2 dates for Amazon as illustrated below.

historical data weekly

Multiple Tickers Historical Data

To do this, we have to create list for several tickers, void dictionary, and go through the list putting data frame in the void dictionary.

ticker_list = ["amzn", "aapl", "ba"]
historical_datas = {}
for ticker in ticker_list:
historical_datas[ticker] = get_data(ticker)

The above translates into data as per the table below.

table data

The set up above comes in handy when combining Yahoo fins with several methods. It helps in gathering historical data for various markets fast.

An example is the dow tickers.

importyahoo_fin.stock_info as si
dow_list = si.tickers_dow()
Importing all the stock at once without doing a single import for each ticker
print("Tickers in Dow Jones:", len(dow_list))
dow_list[0:10]
Tickers in Dow Jones: 30
['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DIS', 'DOW', 'GS', 'HD']
dow_historical = {}
for ticker in dow_list:
dow_historical[ticker] = si.get_data(ticker, start_date="01/01/2020", end_date="01/03/2020", interval="1d")
dow_historical

Outcome,

outcome

We can also download Fundamental Data very easily by using different methods. Below are some examples.

Getting P/E (PRICE-EARNING- RATIO)

Go to Get Quote Table() function.

quote_table = si.get_quote_table("aapl", dict_result=False)
quote_table
{'1y Target Est': 314.55,
'52 Week Range': '174.52 - 327.85',
'Ask': '323.97 x 1300',
'Avg. Volume': 48563118.0,
'Beta (5Y Monthly)': 1.17,
'Bid': '322.30 x 1000',
"Day's Range": '317.23 - 322.35',
'EPS (TTM)': 12.73,
'Earnings Date': 'Jul 28, 2020 - Aug 03, 2020',
'Ex-Dividend Date': 'May 08, 2020',
'Forward Dividend & Yield': '3.28 (1.02%)',
'Market Cap': '1.395T',
'Open': 317.75,
'PE Ratio (TTM)': 25.29,
'Previous Close': 317.94,
'Quote Price': 321.8500061035156,
'Volume': 20185053.0}

In the same manner, we can get the expected dividends from stocks held as below,

quote_table = si.get_quote_table("aapl")
quote_table["Forward Dividend & Yield"]
'3.28 (1.02%)'

Yahoo Finance API allows you to access a wide range of historical data for free. It is one of the best APIs for both beginners and experienced traders. The platform is among various libraries or APIs that facilitates getting real-time Historical data for various market segments and products.