Search code examples
javascriptnode.jssveltesapper

yahooFinance module with sapper


I am making a project where I want to use darta from yahooFinance. I have found this project https://www.npmjs.com/package/yahoo-finance. I have also used the basic sapper template.

Basically what I am trying is to retrive data from YF and show them on the FE.

I gave this piece of code:

<script>
  import yahooFinance from 'yahoo-finance';
  let response;
  async function searchStock (){
    yahooFinance.historical({
      symbol: 'AAPL',
      from: '2020-01-01',
      to: '2020-12-31',
    }, function (err, quotes) {
      console.log(quotes)
    });
  }
</script>

But everytime I try to compile I get: Unexpected token (Note that you need @rollup/plugin-json to import JSON files) 1: { 2: "version": "2020d", ^ 3: "zones": [ 4: "Africa/Abidjan|LMT GMT|g.8 0|01|-2ldXH.Q|48e5",

So I gave tried to import it thus way var yahooFinance = require('yahoo-finance');

But then I get Uncaught (in promise) ReferenceError: require is not defined in to the console.


Solution

  • You won't be able to use the yahoo-finance package on the front end, since it uses Node APIs. Since you're using Sapper, you can use the package in a server route and fetch it from the client.

    Create the file yahoo.json.js and place it in src/routes. Then copy + paste the following into it. This will call the historical method from yahoo-finance and return the result as JSON.

    import yahooFinance from 'yahoo-finance';
    
    export async function get(req, res, next) {
      const response = await new Promise((resolve, reject) => {
        yahooFinance.historical({
          symbol: 'AAPL',
          from: '2020-01-01',
          to: '2020-12-31',
        }, function (err, quotes) {
          if (err) reject(err);
          resolve(quotes);
        });
      })
    
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(response));
    }
    

    You can then call this server route from within a Svelte component. This uses the Sapper preload method to fetch the data before the page renders.

    <script context="module">
      export async function preload() {
        const res = await this.fetch('/yahoo.json');
        const data = await res.json();
    
        return {data};
      }
    
    </script>
    
    <script>
      export let data;
    </script>
    
    {JSON.stringify(data)}
    

    You will likely want to enhance the server route to add request parameters and better error handling, but this shows you how to get it working.