Yahoo Finance API via RapidAPI

Overview

This program loads comma-separated stock symbols from a file named symbols.txt and then queries the Yahoo Finance API using a RapidAPI endpoint. It retrieves prices for every 60 minutes on a max time window.

Prerequisites

Node.js

https://nodejs.org/en/download

RapidAPI API key

https://rapidapi.com/auth/sign-up

Program

 1const unirest = require('unirest');
 2const fs = require('fs');
 3
 4// Function to add a delay
 5function delay(time) {
 6    return new Promise((resolve) => setTimeout(resolve, time));
 7}
 8
 9fs.readFile('symbols.txt', 'utf8', async (err, data) => {
10    if (err) throw err;
11    const symbols = data.split(",");
12    for (let symbol of symbols) {
13        const req = unirest('GET', 'https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-chart');
14        req.query({
15            interval: '60m',
16            symbol: symbol,
17            range: 'max',
18            region: 'US'
19        });
20
21        req.headers({
22            'X-RapidAPI-Key': '',
23            'X-RapidAPI-Host': 'apidojo-yahoo-finance-v1.p.rapidapi.com'
24        });
25
26        req.end(function (res) {
27            if (res.error) throw new Error(res.error);
28            
29            fs.writeFile(`data/${symbol}.json`, JSON.stringify(res.body, null, 2), err => {
30                if (err) throw err;
31                console.log(`Saved data for ${symbol}`);
32            });
33        });
34
35        // Wait for 10 seconds before the next API call
36        await delay(10000);
37    }
38});