금융감독원 API 활용 샘플

 

# -*- coding: utf-8 -*-

# @ 금융감독원 API 를 이용 한 삼성전자 2021 년 임직원 현황 정보 가져오기 (샘플 )

import datetime
import requests
import xml.etree.ElementTree as ET
import matplotlib
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
from pprint import pprint


class ClassSalary():
    def __init__(self, apiKey):
        self.apiKey = apiKey
        self.RtnSalary = 0

    def get_api_url(self, corp_code, bsns_year, reprt_code):
        url = "https://opendart.fss.or.kr/api/empSttus.xml"
        url = url + "?crtfc_key=" + self.apiKey
        url = url + "&corp_code=" + corp_code
        url = url + "&bsns_year=" + bsns_year
        url = url + "&reprt_code=" + reprt_code
        return url

    def get_api_data(self, corp_code, bsns_year, reprt_code):
        apiUrl = self.get_api_url(corp_code, bsns_year, reprt_code)
        # print("API URL : " + apiUrl)

        response = requests.get( apiUrl )
        ### http 통신 결과 코드 확인
        # print("response.status_code : " + str(response.status_code))
        ## http 요청이 성공했을때 API의 리턴값을 가져옵니다.
        if response.status_code == 200:
            contents = response.text
            # print("@@@@@ API 수신 문자열(XML) @@@@@")
            # pprint(str(contents))
            ecosRoot = ET.fromstring(contents)
            # print(str(len(ecosRoot)))

            for row in ecosRoot.iter("list"):
                # print("-----------------------------------------------------------------------------------------------")
                # print( "접수번호:" + str(row.find('rcept_no').text) )
                # print( "법인구분 : Y(유가), K(코스닥), N(코넥스), E(기타):" + str(row.find('corp_cls').text) )
                # print( "공시대상회사의 고유번호(8자리):" + str(row.find('corp_code').text) )
                # print( "법인명:" + str(row.find('corp_name').text) )
                # print( "성별 남, 여:" + str(row.find('sexdstn').text) )
                # print( "사업부문:" + str(row.find('fo_bbm').text) )
                # print( "개정 전 직원 수 정규직:" + str(row.find('reform_bfe_emp_co_rgllbr').text) )
                # print( "개정 전 직원 수 계약직:" + str(row.find('reform_bfe_emp_co_cnttk').text) )
                # print( "개정 전 직원 수 기타:" + str(row.find('reform_bfe_emp_co_etc').text) )
                # print( "정규직 수	상근, 비상근:" + str(row.find('rgllbr_co').text) )
                # print( "정규직 단시간 근로자 수	대표이사, 이사, 사외이사 등:" + str(row.find('rgllbr_abacpt_labrr_co').text) )
                # print( "계약직 수:" + str(row.find('cnttk_co').text) )
                # print( "계약직 단시간 근로자 수:" + str(row.find('cnttk_abacpt_labrr_co').text) )
                # print( "합계:" + str(row.find('sm').text) )
                # print( "avrg_cnwk_sdytrn:" + str(row.find('avrg_cnwk_sdytrn').text) )
                # print( "연간 급여 총액:" + str(row.find('fyer_salary_totamt').text) )
                # print( "1인평균 급여 액:" + str(row.find('jan_salary_am').text) )

                if str(row.find('fo_bbm').text) == "성별합계":
                    self.RtnSalary = self.RtnSalary + int(row.find('jan_salary_am').text.replace(',', ''))

        self.RtnSalary = int( self.RtnSalary / 2 )
        self.RtnSalary = "{:,}".format(self.RtnSalary)

        return self.RtnSalary


if __name__ == '__main__':

    # obj_ClassSalary = ClassSalary("69f9d382fcbf71d3ebb6f72ae345bcf1515943b4")
    # print( "호출결과 : " + str( obj_ClassSalary.get_api_data("00126380", "2021", "11011") ) )

    today       = datetime.date.today()
    nowYear     = today.year
    nowMonth    = today.month
    nowDay      = today.day

    # print( int(nowYear) - 5 )
    # print( int(nowYear) )

    graph_data_year     = []  # 빈 리스트 생성
    graph_data_value    = []  # 빈 리스트 생성

    obj_ClassSalary = ClassSalary("----------------------------")

    for loopCnt in range( ( int( nowYear )-5 ) , int( nowYear ) ):
        print(loopCnt)
        rtnResult                   =   ""
        obj_ClassSalary.RtnSalary   =   0
        rtnResult                   =   str(obj_ClassSalary.get_api_data("00126380", str(loopCnt), "11011"))
        rtnResult = int(rtnResult.replace(',', ''))
        print("호출결과 : " + str(rtnResult))
        graph_data_year.append(loopCnt)
        graph_data_value.append(rtnResult)

    print(graph_data_year)
    print(graph_data_value)

    # 폰트 설정
    font_location = '/Users/yuk-youngmin/Library/Fonts/NanumGothic.otf' # For Mac
    #font_location = 'C:/Windows/Fonts/NanumGothic.ttf' # For Windows
    fm.fontManager.addfont(font_location)
    font_name = fm.FontProperties(fname=font_location).get_name()
    matplotlib.rc('font', family=font_name)


    # 가로 20, 세로 10인 액자를 만듬.
    plt.figure(figsize=(20, 8))
    plt.title("삼성전자 평균연봉 변동그래프")
    plt.xlabel(" Year month ")
    plt.xticks(rotation=45)
    plt.ylabel(" 연봉(억) ")
    plt.plot(graph_data_year, graph_data_value, marker="o")
    plt.ylim([50000000, 150000000])
    plt.grid(True)

    ax = plt.subplot()
    ax.set_xticks(graph_data_year)

    for i in range(len(graph_data_year)):
        height = graph_data_value[i]
        plt.text(graph_data_year[i], height + 0.25, '%.1f' % height, ha='center', va='bottom', size=12)

    plt.show()