Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue Mar 21 2023

Yahoo Finance API - A guide to get stock information in a NodeJs server

Do you have a website, app or perhaps a blog and you want to provide your visitors with some cool financial data, or perhaps some nice stock information, but don't really know how to proceed with your great idea? Look no furter.. In this guide, we will take a look at the Yahoo Finance API and try it out. We will not go through it all, but we will cover the fundamentals.

Looking for a lightweight API for stock prices or exchange rates?

We provide two free APIs for stock prices and exchange rates for free, no need for API keys or sign ups, just fire your requests as much as you want.

Why Yahoo Financial API

Yahoo provides a free API that devs can use to gain access to a ton of financial data. It is easy to use and is a reliable source. They do however, provide a paid subscription if you intend to have it on a commercial project - but for personal projects, it is free.

The prices for the stocks are updated with 15 min of delay, which could be a drawback if you want real time data. But for many cases, 15 min delay should be acceptable.

Prerequisites

  • Create a project and do npm init -y
  • Type npm install express axios in your terminal

Set up a Node server and create a service

As the headline states, we will do this using Node. So lets set up our server and create a service that we will use for this tutorial.

We first create our server with some endpoints. Let's create index.js in the root of your project. And add two endpoints to it. For this guide, we will only use two of the available endpoints that Yahoo provides.

const express = require("express"); const app = express(); const port = 3001; app.get("/chart", async (req, res) => {}); app.get("/stock", async (req, res) => {}); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });

Cool, we will add some code in the empty endpoints later on. But first, lets create our stock service. Create a new file called StockService.js in the root.

const axios = require("axios"); class StockService { async getStockInfo(ticker) { return await axios.get( `https://query1.finance.yahoo.com/v11/finance/quoteSummary/${ticker}?modules=financialData` ); } async getChart(ticker) { return await axios.get( `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}?&interval=1d&range=10d` ); } } module.exports = StockService;

All right. So for this example, we will have two functions. One for getting information about a specific stock - like current price, earnings, buy recommendations from analysts et cetera. And one for getting chart data for the last 10 days with a 1 day interval.

Let's add some code into our endpoints and then we will give it a go.

In index.js, add this code

const StockService = require("./StockService"); const stockService = new StockService(); app.get("/chart", async (req, res) => { const { ticker } = req.query; const stockInfo = await stockService.getChart(ticker); res.send(stockInfo.data); }); app.get("/stock", async (req, res) => { const { ticker } = req.query; const stockInfo = await stockService.getStockInfo(ticker); res.send(stockInfo?.data?.quoteSummary?.result); });

And now, try out the endpoints in the browser or in Postman with some tickers (stock shortnames). Like Apple = AAPL, Microsoft = MSFT.

We start with the stock info endpoint:

http://localhost:3001/stock?ticker=MSFT

This is the full response from the endpoint:

[ { "financialData": { "maxAge": 86400, "currentPrice": { "raw": 270.87, "fmt": "270.87" }, "targetHighPrice": { "raw": 348, "fmt": "348.00" }, "targetLowPrice": { "raw": 212, "fmt": "212.00" }, "targetMeanPrice": { "raw": 286.78, "fmt": "286.78" }, "targetMedianPrice": { "raw": 285, "fmt": "285.00" }, "recommendationMean": { "raw": 1.9, "fmt": "1.90" }, "recommendationKey": "buy", "numberOfAnalystOpinions": { "raw": 45, "fmt": "45", "longFmt": "45" }, "totalCash": { "raw": 99495002112, "fmt": "99.5B", "longFmt": "99,495,002,112" }, "totalCashPerShare": { "raw": 13.366, "fmt": "13.37" }, "ebitda": { "raw": 97945001984, "fmt": "97.95B", "longFmt": "97,945,001,984" }, "totalDebt": { "raw": 77984997376, "fmt": "77.98B", "longFmt": "77,984,997,376" }, "quickRatio": { "raw": 1.656, "fmt": "1.66" }, "currentRatio": { "raw": 1.931, "fmt": "1.93" }, "totalRevenue": { "raw": 204093997056, "fmt": "204.09B", "longFmt": "204,093,997,056" }, "debtToEquity": { "raw": 42.583, "fmt": "42.58" }, "revenuePerShare": { "raw": 27.327, "fmt": "27.33" }, "returnOnAssets": { "raw": 0.14826, "fmt": "14.83%" }, "returnOnEquity": { "raw": 0.39312, "fmt": "39.31%" }, "grossProfits": { "raw": 135620000000, "fmt": "135.62B", "longFmt": "135,620,000,000" }, "freeCashflow": { "raw": 44613373952, "fmt": "44.61B", "longFmt": "44,613,373,952" }, "operatingCashflow": { "raw": 84385996800, "fmt": "84.39B", "longFmt": "84,385,996,800" }, "earningsGrowth": { "raw": -0.113, "fmt": "-11.30%" }, "revenueGrowth": { "raw": 0.02, "fmt": "2.00%" }, "grossMargins": { "raw": 0.68160003, "fmt": "68.16%" }, "ebitdaMargins": { "raw": 0.4799, "fmt": "47.99%" }, "operatingMargins": { "raw": 0.40969002, "fmt": "40.97%" }, "profitMargins": { "raw": 0.33048, "fmt": "33.05%" }, "financialCurrency": "USD" } } ]

As you can see, there is a lot of data and stats. Like cash flow, profits, revenue and so on. If you want to get the current price of the stock, there is an object for that called currentPrice - and the value is updated every 15 minute, when the market is open.

Now lets try the chart endpoint: http://localhost:3001/chart?ticker=MSFT

This is the full response from the API:

{ "chart": { "result": [ { "meta": { "currency": "USD", "symbol": "MSFT", "exchangeName": "NMS", "instrumentType": "EQUITY", "firstTradeDate": 511108200, "regularMarketTime": 1679340475, "gmtoffset": -14400, "timezone": "EDT", "exchangeTimezoneName": "America/New_York", "regularMarketPrice": 270.5, "chartPreviousClose": 256.87, "priceHint": 2, "currentTradingPeriod": { "pre": { "timezone": "EDT", "start": 1679299200, "end": 1679319000, "gmtoffset": -14400 }, "regular": { "timezone": "EDT", "start": 1679319000, "end": 1679342400, "gmtoffset": -14400 }, "post": { "timezone": "EDT", "start": 1679342400, "end": 1679356800, "gmtoffset": -14400 } }, "dataGranularity": "1d", "range": "10d", "validRanges": [ "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max" ] }, "timestamp": [ 1678199400, 1678285800, 1678372200, 1678458600, 1678714200, 1678800600, 1678887000, 1678973400, 1679059800, 1679340475 ], "indicators": { "quote": [ { "high": [ 257.69000244140625, 254.5399932861328, 259.55999755859375, 252.7899932861328, 257.9100036621094, 261.07000732421875, 266.4800109863281, 276.55999755859375, 283.3299865722656, 277.4800109863281 ], "low": [ 253.38999938964844, 250.80999755859375, 251.5800018310547, 247.60000610351562, 245.72999572753906, 255.86000061035156, 259.2099914550781, 263.2799987792969, 276.32000732421875, 269.8500061035156 ], "volume": [ 21473200, 17340200, 26653400, 28321800, 33339700, 33620300, 46028000, 54768800, 69492200, 33176895 ], "close": [ 254.14999389648438, 253.6999969482422, 252.32000732421875, 248.58999633789062, 253.9199981689453, 260.7900085449219, 265.44000244140625, 276.20001220703125, 279.42999267578125, 270.5 ], "open": [ 256.29998779296875, 254.0399932861328, 255.82000732421875, 251.0800018310547, 247.39999389648438, 256.75, 259.9800109863281, 265.2099914550781, 278.260009765625, 276.9800109863281 ] } ], "adjclose": [ { "adjclose": [ 254.14999389648438, 253.6999969482422, 252.32000732421875, 248.58999633789062, 253.9199981689453, 260.7900085449219, 265.44000244140625, 276.20001220703125, 279.42999267578125, 270.5 ] } ] } } ], "error": null } }

And there we have it. This data can be great to use if you want to show historical data in a chart for example, like stock price movements for the last year or so.

Summary

In this guide, we showed briefly how we can use Yahoo Finance API in a NodeJs project, and we called two of their endpoints to get some data.

We just touched a small part of their API, there is a lot more to explore. This guide is showing more into the available data and if you want to get more information than we showed in this guide, check the link out.

Thanks for reading!

signatureTue Mar 21 2023
See all our articles