GCP/Apps Script

Apps Script로 어제 KOSPI 지수 Telegram으로 아침에 조간 브리핑 받기

whistory 2023. 1. 9. 08:45
반응형

 

Nasdaq이랑, 어제자 증권뉴스만 정보를 가져왔다.

정작 kospi 지수를 가져오지를 않았다.

 

 

 

https://www.data.go.kr/tcs/dss/selectApiDataDetailView.do?publicDataPk=15094807

 

금융위원회_지수시세정보

한국거래소에서 제공하는 지수의 시세 정보 주가지수시세, 채권지수시세, 파생상품지수시세에 대한 오퍼레이션을 제공한다.

www.data.go.kr

 

 

 

 

/**
 * KOSPI 지수 전일자 조회 
 */
function goodMorningKospi() {
  const returnType = "json"; // JSON || XML
  const yesterday = getTodayDate("", "yesterday");

  const kospi_url = `https://apis.data.go.kr/1160100/service/GetMarketIndexInfoService/getStockMarketIndex?pageNo=1&numOfRows=1000&idxNm=%EC%BD%94%EC%8A%A4%ED%94%BC&resultType=${returnType}&basDt=${yesterday}&serviceKey=${dataServiceKey}`;
  const kospi_response = UrlFetchApp.fetch(url, {
    method : "GET",
    header:{
      "contentType" : "application/json"
    }
  });

  const json = response.getContentText();
  const returndData = JSON.parse(json);
  const item = returndData.response.body.items.item[0];

  const clpr = item.clpr;   // 종가
  const vs = item.vs;       // 전일대비
  const fltRt = item.fltRt; // 전일대비퍼
  const hipr = item.hipr;   // 최고가
  const lopr = item.lopr;   // 최저가

  const message = `종가\\t: ${clpr}\\r\\n전일대비\\t: ${vs}(${fltRt})\\r\\n최고가\\t: ${hipr}\\r\\n최저가\\t: ${lopr}\\r\\n`;

  console.log(message);
  sendTelegramMsg(message);
}

 

 

 

 

 

 

 

주말의 경우에는, 데이터가 없어서 trigger 실행 시 에러가 발생한다.

 

 

 

body 에 totalCount 가 0 이상일 경우에만 실행되도록 로직을 추가한다.

/**
 * 코스피 + 네이버 증시 시황 전일자 조회
 */
function goodMorningKospi() {
  const dateCondition = getTodayDate("-", "yesterday");

  const returnType  = "json";
  const yesterday   = getTodayDate("", "yesterday");
  const kospi_url   = `https://apis.data.go.kr/1160100/service/GetMarketIndexInfoService/getStockMarketIndex?pageNo=1&numOfRows=1000&idxNm=%EC%BD%94%EC%8A%A4%ED%94%BC&resultType=${returnType}&basDt=${yesterday}&serviceKey=${dataServiceKey}`;

  const kospi_response  = UrlFetchApp.fetch(kospi_url, {
    method : "GET",
    header:{
      "contentType" : "application/json"
    }
  });

  const json        = kospi_response.getContentText();
  const returndData = JSON.parse(json);
  const cnt         = returndData.response.body.totalCount;

  if ( cnt > 0 ) {
    const item        = returndData.response.body.items.item[0];

    const clpr  = item.clpr;  // 종가
    const vs    = item.vs;    // 전일대비
    const fltRt = item.fltRt; // 전일대비퍼
    const hipr  = item.hipr;  // 최고가
    const lopr  = item.lopr;  // 최저가

    var message = `[${dateCondition} KOSPI 지수]\\r\\n\\r\\n`
                + `종가 : ${clpr}\\r\\n전일대비 : ${vs} (${fltRt})\\r\\n최고가 : ${hipr}\\r\\n최저가 : ${lopr}\\r\\n\\r\\n`;
    
    const url = `https://finance.naver.com/news/mainnews.naver?date=${dateCondition}`;
    const content = UrlFetchApp.fetch(url).getContentText("euc-kr");    // 한글 깨짐방지를 위해 인코딩 처리
    const $ = Cheerio.load(content);
    const $listGroup = $(".newsList").children("li");
    const collections = []
    $listGroup.each(function(i, elem) {
      collections.push({
          data  : $(this).find('a').text()
        , link  : "<https://finance.naver.com>"+$(this).find('a').attr("href")
      })
    })
    
    message += `[${dateCondition} 시황]\\r\\n`;

    for (i in collections) {
      const data = collections[i].data;
      const link = collections[i].link;
      if ( data.indexOf("시황") > 0 || data.indexOf("마켓") > 0 ) {
        message += `\\r\\n■ ${data}`;
      }
    }
    // console.log(message);

    sendTelegramMsg(message);
  }
}

 

 

 

완성된 메세지 모습

 

 

 

 

 

 

코스닥 정보를 가져오고 싶으면,

api 호출 시 파라미터에, inxNm 에 '코스닥' 을 넣어주면 코스닥 정보를 가져온다.

 

 

 

 

 

 

 

반응형