LoginSignup
2
0

More than 1 year has passed since last update.

YahooAPIを用いた銘柄情報取得

Last updated at Posted at 2022-09-17

はじめに

どうも、emonです。
今回は、YahooFinanceに保存されている情報をAPIを用いて取得します。
今回、APIをより扱いやすくする為、OSSのnode-yahoo-finance2を用いて取得してみようと思います。
■環境

  • macOS
  • Node.js
  • npm(パッケージ管理)
  • Express(WEBサーバ)
  • javascript

目次

  1. 環境構築
  2. APIを叩いてデータを取得
  3. 動作確認
  4. エンドポイントの作成
  5. 参考文献

環境構築

  1. package.json及び必要ライブラリのインストール

    npm init
    npm install express
    npm install yahoo-finance2
    
  2. アプリルートディレクトリ配下にmodulesフォルダを作成し、quate.jsを作成する。

  3. app.jsを作成する。

  4. 以下のようなフォルダ構成になっていればOKです。

    1.フォルダ構成
    |- modules
    |-- quate.js
    |- node_modules
    |- app.js
    |- package-lock.json
    |- package.json
    

APIを叩いてデータを取得

  1. quate.jsに以下を追加する。今回は、例としてアップルの情報を取得する。

    1./modules/quate.js
    import yahooFinance from 'yahoo-finance2';
    
    // quote
    export const get = async () => {
        try {
            const data = await yahooFinance.quote('AAPL');
            return data;
        } catch (e) {
            return e;
        }
    };
    

エンドポイントの作成

  1. expressを用いてWEBサーバを構築する。

    1.app.js
    /* 1. appにインスタンスにexpressを格納*/
    const app = express();
    
    /* 2. 3000番ポートで起動する。*/
    const port = 3000;
    const server = app.listen(port, () => {
        console.log("listening to PORT:" + server.address().port);
    });
    
    
  2. app.jsに'/quate/get'のルーティングを追加する。

    1.app.js
    import * as quate from './modules/quate.js';
    
    // quate
    router.get("/quate/get", (req, res, next) => {
      const quateGet = quate.get();
      quateGet.then((result) => {
        res.json(result);
      });
    });
    

動作確認

  1. WEBサーバを起動させる

    node app.js
    
  2. 任意のブラウザを起動させ、'localhost:3000/quate/get'を叩く。以下の画像のようにデータが取得できていればOKです。
    スクリーンショット 2022-09-11 15.18.27.png

以上、YahooAPIを用いた株データの取得方法でした。

参考文献

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0