jonghhhh commited on
Commit
508403c
·
verified ·
1 Parent(s): d6b7cd0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -135
app.py CHANGED
@@ -2,161 +2,72 @@ import streamlit as st
2
  import requests
3
  import pandas as pd
4
 
5
- # 화면 너비 조정
6
- st.markdown(
7
- """
8
- <style>
9
- .reportview-container .main .block-container{
10
- max-width: 90%; /* 화면 크기를 90%로 설정 */
11
- padding-top: 1rem;
12
- padding-right: 1rem;
13
- padding-left: 1rem;
14
- padding-bottom: 1rem;
15
- }
16
- </style>
17
- """,
18
- unsafe_allow_html=True,
19
- )
20
 
21
- # API 키와 기본 URL 설정
22
- api_key = "YOUR_API_KEY_HERE"
23
- base_url = "https://ecos.bok.or.kr/api/"
24
-
25
- # 서비스 통계 목록 API 호출 함수
26
- def get_service_statistics(start=1, end=10, stat_code=None):
27
- url = f"{base_url}StatisticTableList/{api_key}/json/kr/{start}/{end}"
28
- if stat_code:
29
- url += f"/{stat_code}"
30
- response = requests.get(url)
31
- if response.status_code == 200:
32
- return response.json()
33
- else:
34
- st.error("데이터를 불러오는 데 실패했습니다.")
35
- st.write(response.text)
36
- return None
37
-
38
- # 통계용어사전 API 호출 함수
39
- def get_statistical_glossary(term, start=1, end=10):
40
- url = f"{base_url}StatisticWord/{api_key}/json/kr/{start}/{end}/{term}"
41
- response = requests.get(url)
42
- if response.status_code == 200:
43
- return response.json()
44
- else:
45
- st.error("데이터를 불러오는 데 실패했습니다.")
46
- st.write(response.text)
47
- return None
48
-
49
- # 통계 세부항목 목록 API 호출 함수
50
- def get_statistic_detail_items(stat_code, start=1, end=10):
51
- url = f"{base_url}StatisticItemList/{api_key}/json/kr/{start}/{end}/{stat_code}"
52
  response = requests.get(url)
53
  if response.status_code == 200:
54
- return response.json()
 
 
55
  else:
56
- st.error("데이터를 불러오는 실패했습니다.")
57
- st.write(response.text)
58
  return None
59
 
60
- # 통계 조회 조건 설정 API 호출 함수
61
- def get_statistic_search_conditions(stat_code, period, start_date, end_date, start=1, end=10):
62
- url = f"{base_url}StatisticSearch/{api_key}/json/kr/{start}/{end}/{stat_code}/{period}/{start_date}/{end_date}"
63
  response = requests.get(url)
64
  if response.status_code == 200:
65
- return response.json()
 
 
66
  else:
67
- st.error("데이터를 불러오는 실패했습니다.")
68
- st.write(response.text)
69
  return None
70
 
71
- # 100대 통계지표 API 호출 함수
72
  def get_top_100_statistics(start=1, end=10):
73
- url = f"{base_url}KeyStatisticList/{api_key}/json/kr/{start}/{end}"
74
  response = requests.get(url)
75
  if response.status_code == 200:
76
- return response.json()
 
 
77
  else:
78
- st.error("데이터를 불러오는 실패했습니다.")
79
- st.write(response.text)
80
  return None
81
 
82
- # 통계 메타 데이터베이스 API 호출 함수
83
- def get_statistical_metadata(data_name, start=1, end=10):
84
- url = f"{base_url}StatisticMeta/{api_key}/json/kr/{start}/{end}/{data_name}"
85
- response = requests.get(url)
86
- if response.status_code == 200:
87
- return response.json()
88
- else:
89
- st.error("데이터를 불러오는 데 실패했습니다.")
90
- st.write(response.text)
91
- return None
92
-
93
- # JSON 데이터를 DataFrame으로 변환하여 표시
94
- def display_data_as_table(data):
95
- if data:
96
- if isinstance(data, dict):
97
- if any(key in data for key in ["StatisticItemList", "StatisticTableList", "StatisticWordList", "KeyStatisticList", "StatisticMeta"]):
98
- for key in data:
99
- if key in ["StatisticItemList", "StatisticTableList", "StatisticWordList", "KeyStatisticList", "StatisticMeta"]:
100
- df = pd.DataFrame(data[key]["row"])
101
- st.dataframe(df)
102
- else:
103
- st.write("데이터를 표시할 수 없습니다.")
104
- else:
105
- st.write("데이터 형식이 잘못되었습니다.")
106
- else:
107
- st.write("데이터를 로드할 수 ��습니다.")
108
-
109
  # Streamlit 앱 구성
110
  st.title("한국은행 ECOS API 데이터 조회")
111
- st.sidebar.header("API 항목 선택")
112
-
113
- # 사이드바에서 선택할 수 있는 항목
114
- option = st.sidebar.selectbox(
115
- "조회할 항목을 선택하세요:",
116
- ("서비스 통계 목록", "통계용어사전", "통계 세부항목 목록", "통계 조회 조건 설정", "100대 통계지표", "통계 메타DB")
117
- )
118
-
119
- # 입력 양식 구성
120
- if option == "서비스 통계 목록":
121
- stat_code = st.text_input("통계표코드 입력 (선택사항):")
122
- if st.button("실행"):
123
- data = get_service_statistics(stat_code=stat_code)
124
- display_data_as_table(data)
125
 
126
- elif option == "통계용어사전":
127
- term = st.text_input("용어 입력:")
128
- if st.button("실행"):
129
- if term:
130
- data = get_statistical_glossary(term)
131
- display_data_as_table(data)
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- elif option == "통계 세부항목 목록":
134
- stat_code = st.text_input("통계표코드 입력:")
135
- if st.button("실행"):
136
- if stat_code:
137
- data = get_statistic_detail_items(stat_code)
138
- display_data_as_table(data)
139
-
140
- elif option == "통계 조회 조건 설정":
141
- stat_code = st.text_input("통계표코드 입력:")
142
- period = st.text_input("주기 입력 (예: A, Q, M):")
143
- start_date = st.text_input("검색 시작일자 입력 (예: 2015, 2015Q1, 201501, 20150101):")
144
- end_date = st.text_input("검색 종료일자 입력 (예: 2021, 2021Q1, 202101, 20210101):")
145
- if st.button("실행"):
146
- if stat_code and period and start_date and end_date:
147
- data = get_statistic_search_conditions(stat_code, period, start_date, end_date)
148
- display_data_as_table(data)
149
 
150
- elif option == "100대 통계지표":
151
- start = st.text_input("요청 시작 건수 (예: 1):", "1")
152
- end = st.text_input("요청 종료 건수 (예: 10):", "10")
153
- if st.button("실행"):
154
- data = get_top_100_statistics(start=start, end=end)
155
- display_data_as_table(data)
156
 
157
- elif option == "통계 메타DB":
158
- data_name = st.text_input("데이터명 입력:")
159
- if st.button("실행"):
160
- if data_name:
161
- data = get_statistical_metadata(data_name)
162
- display_data_as_table(data)
 
2
  import requests
3
  import pandas as pd
4
 
5
+ # API 설정
6
+ api_key = "Z2FNKPFTMDSTHHR60KS4"
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # 통계 코드 조회 함수
9
+ def get_statistic_codes():
10
+ url = f"https://ecos.bok.or.kr/api/StatisticTableList/{api_key}/json/kr/1/1000"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  response = requests.get(url)
12
  if response.status_code == 200:
13
+ data = response.json()
14
+ df = pd.DataFrame(data['StatisticTableList']['row'])
15
+ return df[['STAT_CODE', 'STAT_NAME']]
16
  else:
17
+ st.error(f"Failed to retrieve data: {response.status_code}")
 
18
  return None
19
 
20
+ # 통계 데이터 조회 함수
21
+ def get_statistic_data(stat_code, period, start_date, end_date):
22
+ url = f"https://ecos.bok.or.kr/api/StatisticSearch/{api_key}/json/kr/1/1000/{stat_code}/{period}/{start_date}/{end_date}"
23
  response = requests.get(url)
24
  if response.status_code == 200:
25
+ data = response.json()
26
+ df = pd.DataFrame(data['StatisticSearch']['row'])
27
+ return df
28
  else:
29
+ st.error(f"Failed to retrieve data: {response.status_code}")
 
30
  return None
31
 
32
+ # 100대 통계지표 조회 함수
33
  def get_top_100_statistics(start=1, end=10):
34
+ url = f"https://ecos.bok.or.kr/api/KeyStatisticList/{api_key}/json/kr/{start}/{end}"
35
  response = requests.get(url)
36
  if response.status_code == 200:
37
+ data = response.json()
38
+ df = pd.DataFrame(data['KeyStatisticList']['row'])
39
+ return df
40
  else:
41
+ st.error(f"Failed to retrieve data: {response.status_code}")
 
42
  return None
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # Streamlit 앱 구성
45
  st.title("한국은행 ECOS API 데이터 조회")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ # 통계 코드 조회 및 선택
48
+ st.header("1. 통계 코드 조회")
49
+ stat_codes_df = get_statistic_codes()
50
+ if stat_codes_df is not None:
51
+ st.dataframe(stat_codes_df)
52
+ selected_code = st.selectbox("조회할 통계 코드를 선택하세요:", stat_codes_df['STAT_CODE'])
53
+
54
+ # 통계 데이터 조회 및 출력
55
+ st.header("2. 통계 데이터 조회")
56
+ period = st.text_input("조회 주기 입력 (예: A, Q, M):", "A")
57
+ start_date = st.text_input("검색 시작일자 입력 (예: 2015, 2015Q1, 201501, 20150101):", "2015")
58
+ end_date = st.text_input("검색 종료일자 입력 (예: 2021, 2021Q1, 202101, 20210101):", "2021")
59
+
60
+ if st.button("통계 데이터 조회"):
61
+ stat_data_df = get_statistic_data(selected_code, period, start_date, end_date)
62
+ if stat_data_df is not None:
63
+ st.dataframe(stat_data_df)
64
 
65
+ st.title("한국은행 ECOS API 데이터 조회")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ # 100대 통계지표 실시간 확인
68
+ st.header("100대 통계지표 실시간 확인")
 
 
 
 
69
 
70
+ if st.button("100대 통계지표 전체 조회"):
71
+ top_100_df = get_top_100_statistics()
72
+ if top_100_df is not None:
73
+ st.dataframe(top_100_df)