-
Notifications
You must be signed in to change notification settings - Fork 94
/
dart_list.py
187 lines (162 loc) · 5.71 KB
/
dart_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#-*- coding:utf-8 -*-
# 2020-2023 FinanceData.KR http://financedata.kr fb.com/financedata
import requests
import zipfile
import io
import os
import pandas as pd
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
# 1. 공시정보 - 공시검색(목록)
def list(api_key, corp_code='', start=None, end=None, kind='', kind_detail='', final=False):
start = pd.to_datetime(start) if start else pd.to_datetime('1900-01-01')
end = pd.to_datetime(end) if end else datetime.today()
url = 'https://opendart.fss.or.kr/api/list.json'
params = {
'crtfc_key': api_key,
'corp_code': corp_code,
'bgn_de': start.strftime('%Y%m%d'),
'end_de': end.strftime('%Y%m%d'),
'last_reprt_at': 'Y' if final else 'N', # 최종보고서 여부
'page_no': 1,
'page_count': 100,
}
if kind:
params['pblntf_ty'] = kind # 공시유형: 기본값 'A'=정기공시
if kind_detail:
params['pblntf_detail_ty'] = kind_detail
r = requests.get(url, params=params)
try:
tree = ET.XML(r.content)
status = tree.find('status').text
message = tree.find('message').text
if status != '000':
raise ValueError({'status': status, 'message': message})
except ET.ParseError as e:
jo = r.json()
if jo['status'] != '000':
print(ValueError(r.text))
jo = r.json()
if 'list' not in jo:
return pd.DataFrame()
df = pd.DataFrame(jo['list'])
# paging
for page in range(2, jo['total_page']+1):
params['page_no'] = page
r = requests.get(url, params=params)
jo = r.json()
df = pd.concat([df, pd.DataFrame(jo['list'])])
df = df.reset_index(drop=True)
return df
# 1-2. 공시정보 - 기업개황
def company(api_key, corp_code):
url = 'https://opendart.fss.or.kr/api/company.json'
params = {
'crtfc_key': api_key,
'corp_code': corp_code,
}
r = requests.get(url, params=params)
try:
tree = ET.XML(r.content)
status = tree.find('status').text,
message = tree.find('message').text
if status != '000':
raise ValueError({'status': status, 'message': message})
except ET.ParseError as e:
pass
return r.json()
# 1-2. 공시정보 - 기업개황: 지정된 이름(name)을 포함하는 회사들의 corp_code 리스트를 반환
def company_by_name(api_key, corp_code_list):
url = 'https://opendart.fss.or.kr/api/company.json'
params = {
'crtfc_key': api_key,
'corp_code': '',
}
company_list = []
for corp_code in corp_code_list:
params['corp_code'] = corp_code
r = requests.get(url, params=params)
company_list.append(r.json())
return company_list
# 1-3. 공시정보 - (사업보고서) 공시서류원본파일
def document(api_key, rcp_no, cache=True):
url = 'https://opendart.fss.or.kr/api/document.xml'
params = {
'crtfc_key': api_key,
'rcept_no': rcp_no,
}
r = requests.get(url, params=params)
try:
tree = ET.XML(r.text)
status = tree.find('status').text
message = tree.find('message').text
if status != '000':
raise ValueError({'status': status, 'message': message})
except ET.ParseError as e:
pass
zf = zipfile.ZipFile(io.BytesIO(r.content))
info_list = zf.infolist()
fnames = sorted([info.filename for info in info_list])
xml_data = zf.read(fnames[0])
try:
xml_text = xml_data.decode('euc-kr')
except UnicodeDecodeError as e:
xml_text = xml_data.decode('utf-8')
except UnicodeDecodeError as e:
xml_text = xml_data
return xml_text
# 1-3. 공시정보 - (사업보고서, 감사보고서) 공시서류원본문서파일
def document_all(api_key, rcp_no, cache=True):
url = 'https://opendart.fss.or.kr/api/document.xml'
params = {
'crtfc_key': api_key,
'rcept_no': rcp_no,
}
r = requests.get(url, params=params)
try:
tree = ET.XML(r.text)
status = tree.find('status').text
message = tree.find('message').text
if status != '000':
raise ValueError({'status': status, 'message': message})
except ET.ParseError as e:
pass
zf = zipfile.ZipFile(io.BytesIO(r.content))
info_list = zf.infolist()
fnames = sorted([info.filename for info in info_list])
xml_text_list = []
for fname in fnames:
xml_data = zf.read(fname)
try:
xml_text = xml_data.decode('euc-kr')
except UnicodeDecodeError as e:
xml_text = xml_data.decode('utf-8')
except UnicodeDecodeError as e:
xml_text = xml_data
xml_text_list.append(xml_text)
return xml_text_list
# 1-4 고유번호: api/corpCode.xml
def corp_codes(api_key):
url = 'https://opendart.fss.or.kr/api/corpCode.xml'
params = { 'crtfc_key': api_key, }
r = requests.get(url, params=params)
try:
tree = ET.XML(r.content)
status = tree.find('status').text
message = tree.find('message').text
if status != '000':
raise ValueError({'status': status, 'message': message})
except ET.ParseError as e:
pass
zf = zipfile.ZipFile(io.BytesIO(r.content))
xml_data = zf.read('CORPCODE.xml')
# XML to DataFrame
tree = ET.XML(xml_data)
all_records = []
element = tree.findall('list')
for i, child in enumerate(element):
record = {}
for i, subchild in enumerate(child):
record[subchild.tag] = subchild.text
all_records.append(record)
return pd.DataFrame(all_records)