import streamlit as st import requests import pandas as pd # API 키 설정 api_key = "Z2FNKPFTMDSTHHR60KS4" # 통계 코드 조회 함수 def get_statistic_codes(): url = f"https://ecos.bok.or.kr/api/StatisticTableList/{api_key}/json/kr/1/1000" response = requests.get(url) if response.status_code == 200: data = response.json() df = pd.DataFrame(data['StatisticTableList']['row']) df['코드와 이름'] = df['STAT_CODE'] + ": " + df['STAT_NAME'] return df[['STAT_CODE', '코드와 이름']] else: st.error(f"Failed to retrieve data: {response.status_code}") return None # 통계 데이터 조회 함수 def get_statistic_data(stat_code, period, start_date, end_date): url = f"https://ecos.bok.or.kr/api/StatisticSearch/{api_key}/json/kr/1/1000/{stat_code}/{period}/{start_date}/{end_date}" response = requests.get(url) if response.status_code == 200: data = response.json() if 'StatisticSearch' in data: df = pd.DataFrame(data['StatisticSearch']['row']) return df else: st.error("데이터가 없습니다. 입력한 조건을 확인하세요.") return None else: st.error(f"Failed to retrieve data: {response.status_code}") return None # 100대 통계지표 전체 조회 함수 def get_top_100_statistics(): url = f"https://ecos.bok.or.kr/api/KeyStatisticList/{api_key}/json/kr/1/1000" response = requests.get(url) if response.status_code == 200: data = response.json() if 'KeyStatisticList' in data: df = pd.DataFrame(data['KeyStatisticList']['row']) return df else: st.error("100대 통계지표 데이터를 찾을 수 없습니다.") return None else: st.error(f"Failed to retrieve data: {response.status_code}") return None # Streamlit 앱 구성 st.title("한국은행 ECOS API 데이터 조회") # 왼쪽 사이드바에서 선택 메뉴 구성 menu = st.sidebar.selectbox( "메뉴를 선택하세요", ("통계 코드 조회 및 데이터 분석", "100대 통계지표 실시간 확인") ) if menu == "통계 코드 조회 및 데이터 분석": st.header("통계 코드 조회 및 데이터 분석") # 통계 코드 조회 및 선택 stat_codes_df = get_statistic_codes() if stat_codes_df is not None: selected_code_name = st.selectbox("조회할 통계 코드를 선택하세요:", stat_codes_df['코드와 이름']) selected_code = selected_code_name.split(": ")[0] # 통계 코드만 추출 # 통계 데이터 조회 및 출력 period = st.text_input("조회 주기 입력 (예: A, Q, M):", "A") start_date = st.text_input("검색 시작일자 입력 (예: 2015, 2015Q1, 201501, 20150101):", "2015") end_date = st.text_input("검색 종료일자 입력 (예: 2021, 2021Q1, 202101, 20210101):", "2021") if st.button("통계 데이터 조회"): stat_data_df = get_statistic_data(selected_code, period, start_date, end_date) if stat_data_df is not None: st.write(f"선택한 통계 코드: {selected_code}") st.dataframe(stat_data_df) # Excel 파일로 저장 st.write("데이터를 Excel 파일로 저장하려면 아래 버튼을 클릭하세요.") if st.button("Excel로 저장"): stat_data_df.to_excel(f"{selected_code}_data.xlsx", index=False) st.success(f"데이터가 {selected_code}_data.xlsx 파일로 저장되었습니다.") elif menu == "100대 통계지표 실시간 확인": st.header("100대 통계지표 실시간 확인") top_100_df = get_top_100_statistics() if top_100_df is not None: st.dataframe(top_100_df)