LoginSignup
2
1

More than 3 years have passed since last update.

日々の株価を手軽にGoogleAppScriptsで取得する

Last updated at Posted at 2019-12-25

やること

毎日15時すぎにその日の株価を取得し、スプレッドシートに記録していくスクリプトを作成します。
自分の保有資産の毎日の推移をさくっと見ることができるようにします。

スクリプト

サンプルとしてLIFULL(2120)の株価を取得することとします。


function putRowAndPrice() {
  const ticker = '2120.T';
  const url = 'https://stocks.finance.yahoo.co.jp/stocks/detail/?code=' + ticker;

  const book = SpreadsheetApp.getActiveSpreadsheet();
  const sheet= book.getSheetByName("シート1");
  const currentDayPrice = fetchLatestPrice();

  const date = new Date();
  // arrayの最初の要素にarrayにしないとsetValuesはエラーになる
  const price = [ 
    [Utilities.formatDate(date, 'Asia/Tokyo', 'yyyy/MM/dd'), currentDayPrice]
  ]
  sheet.insertRowAfter(1);
  sheet.getRange('A2:B2').setValues(price);

}

function fetchLatestPrice() {
  const response = UrlFetchApp.fetch(url);
  const html = response.getContentText('UTF-8');
  // 直前のクラス名
  const beforeTarget = html.split('realTimChangeMod');
  // 取得したい要素の文字列
  const target = beforeTarget[1].split('stoksPrice">');
  const price = target[1].split("</td>");

  return price[0];
}

上記でスクリプト編集画面でputRowAndPrice 関数を実行すれば、その日の株価を
A2:B2のセルに吐き出すことができました。

スクリーンショット 2020-11-15 20.59.27.png

トリガーの設定

平日の15時10分にスクリプトが動くように設定します。
GASのGUI画面からでは特定の日の特定の時間には設定ができないのでスクリプト上で設定をします。

function setTrigger() {
  // 0 6 は 日曜、土曜
  const execDays = [1, 2, 3, 4, 5];
  const date = new Date();
  const dayOfTheWeek = date.getDay();

  if (execDays.includes(dayOfTheWeek)) {
    date.setDate(setTime.getDate() + 1)
    date.setHours(15);
    date.setMinutes(10); 
    ScriptApp.newTrigger('exec').timeBased().at(date).create();  
  }
}

function exec() {
  setTrigger();
  putRowAndPrice();
}

一度スクリプト画面からsetTriggerメソッドを実行する必要があります。
実行後に スクリプト画面>編集>現在のプロジェクトのトリガー
設定されたトリガーを確認することができます。

スクリーンショット 2020-11-15 21.12.22.png

スクリーンショット 2020-11-15 20.39.25.png

終わりに

上記で指定した銘柄の日々の終値を記録できるようになりました。
この記事を8割方書き終わった後にこんなライブラリを見つけたので、そちらで取得してみたほうがより便利、かつ面白いことができるかもしれません。

2
1
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
1