krxpy 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
krxpy-0.0.3/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
krxpy-0.0.3/PKG-INFO ADDED
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.1
2
+ Name: krxpy
3
+ Version: 0.0.3
4
+ Summary: KRX Data Crawling ...
5
+ Home-page: https://github.com/YongBeomKim/krxpy
6
+ Author: momukji lab
7
+ Author-email: ybkim@momukji.com
8
+ License: MIT
9
+ Keywords: krxpy
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: pytip
18
+ Requires-Dist: pandas
19
+ Requires-Dist: lxml
20
+ Requires-Dist: tqdm
21
+ Requires-Dist: requests
22
+
23
+ # [data.krx.co.kr](http://data.krx.co.kr/contents/MDC/MAIN/main/index.cmd) 데이터 수집기 함수
24
+ > 증권거래소 정보데이터 시스템
25
+ [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE)
26
+ [![Docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://domschl.github.io/ml-indie-tools/index.html)
27
+ [![PyPI version fury.io](https://badge.fury.io/py/ml-indie-tools.svg)](https://pypi.python.org/pypi/ml-indie-tools/)
28
+
29
+
30
+ ## Version
31
+ 0.0.1 - datetime object & string Integration management in Python
32
+
33
+ © 2024 GitHub : https://github.com/YongBeomKim
krxpy-0.0.3/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # [data.krx.co.kr](http://data.krx.co.kr/contents/MDC/MAIN/main/index.cmd) 데이터 수집기 함수
2
+ > 증권거래소 정보데이터 시스템
3
+ [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE)
4
+ [![Docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://domschl.github.io/ml-indie-tools/index.html)
5
+ [![PyPI version fury.io](https://badge.fury.io/py/ml-indie-tools.svg)](https://pypi.python.org/pypi/ml-indie-tools/)
6
+
7
+
8
+ ## Version
9
+ 0.0.1 - datetime object & string Integration management in Python
10
+
11
+ © 2024 GitHub : https://github.com/YongBeomKim
@@ -0,0 +1,11 @@
1
+ from . import stock
2
+ from ._kofia import kofia
3
+
4
+ __all__ = [
5
+ 'stock', # 기업정보
6
+ 'price', # 실시간 가격정보
7
+ 'trader', # 거래원 데이터
8
+ 'calender', # 증시 캘린더
9
+ ]
10
+
11
+ __version__ = '0.0.1'
@@ -0,0 +1,3 @@
1
+ # http://freesis.kofia.or.kr/
2
+ # 금융투자협회 데이터 수집기
3
+ from .kofia import kofia
@@ -0,0 +1,126 @@
1
+ from .base import *
2
+
3
+
4
+ class HeaderOfKofia(Header):
5
+ r"""kofia 금융투자협회 수집을 위한 공용 데이터 클래스
6
+ - `_header()` : 웹 크롤링을 위한 url & header
7
+ - `_json()` : Post 호출을 위한 Form Data
8
+ - `_get()` : 모든 데이터를 활용하여 호출작업 진행"""
9
+
10
+ def _header(self) -> dict:
11
+ r"""Post url 파라미터 정의"""
12
+
13
+ # Params : Referer 사이트 주소값 조합을 위한 파라미터
14
+ url = "http://freesis.kofia.or.kr/meta/getMetaDataList.do"
15
+ ref_path = 'stat/FreeSIS.do'
16
+ ref_queryset = {
17
+ 'parentDivId':'MSIS10000000000000',
18
+ 'serviceId':'STATSCU0100000060'
19
+ }
20
+
21
+ # Process : 웹 수집을 위한 Header
22
+ url_parts = urlparse(url)
23
+ headers: dict = {}
24
+ headers["Content-Type"] = "application/json; charset=utf-8"
25
+ headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64; rv:101.0) Gecko/20100101 Firefox/101.0"
26
+ headers["Host"] = url_parts.netloc
27
+ headers["Origin"] = "http://" + url_parts.netloc
28
+ headers["Referer"] = url_parts._replace(
29
+ path = ref_path,
30
+ query = urlencode(ref_queryset)
31
+ ).geturl()
32
+
33
+ content = {
34
+ "url": url,
35
+ "headers": headers
36
+ }
37
+ return content
38
+
39
+ def _json(self, start:str=None, end:str=None, gap:int=7, code:str=None, market:int=None):
40
+ r"""날짜 파라미터 내용확인 및 Post 수집을 위한 Json Data 생성
41
+ (str) start : 데이터 수집 시작날짜
42
+ (str) end : 데이터 수집 종료날짜
43
+ (int) gap : 현재로 부터 시작날짜 간격
44
+ (str) code : API 호출을 위한 작업구분 코드
45
+ (int) market: Kospi, Kosdaq 구분자
46
+ """
47
+
48
+ # 날짜 파라미터 생성 및 유효성 검사
49
+ if start == None:
50
+ start = (self._now_date() - datetime.timedelta(gap)).date()
51
+ if end == None:
52
+ end = self._now_date().date()
53
+ start, end = self._date_string(start), self._date_string(end)
54
+
55
+ # Post 호출을 위한 Json 데이터 생성
56
+ json_data: dict = {"dmSearch":{"tmpV40":"1","tmpV41":"1","tmpV1":"D"}}
57
+ json_data["dmSearch"]["tmpV45"] = start
58
+ json_data["dmSearch"]["tmpV46"] = end
59
+
60
+ # 추가작업 Case 1
61
+ # self.credit() : 증시동향 (일간) 데이터
62
+ if code == 'STATSCU0100000130BO':
63
+ if market in [1,2]: # market : KOSPI, KOSDAQ
64
+ del json_data["dmSearch"]["tmpV46"]
65
+ json_data["dmSearch"]["tmpV74"] = f"{market},0,,1"
66
+
67
+ # 추가작업 Case 2
68
+ # self.credit_trader() : 참여자별 대차거래
69
+ if code == 'STATSCU0100000150BO':
70
+ del json_data["dmSearch"]["tmpV1"]
71
+ del json_data["dmSearch"]["tmpV45"]
72
+ del json_data["dmSearch"]["tmpV46"]
73
+ json_data["dmSearch"]["tmpV30"] = start
74
+ json_data["dmSearch"]["tmpV31"] = end
75
+
76
+ # 보정작업을 마친 날짜 데이터 출력
77
+ json_data["dmSearch"]["OBJ_NM"] = code
78
+ content = {
79
+ 'start':start,
80
+ 'end':end,
81
+ 'jsonData':json_data,
82
+ }
83
+ return content
84
+
85
+ def _get(self,
86
+ start:str = None, end:str = None, gap:int = 7,
87
+ code:str = '', column:dict = None, market:str = None
88
+ ) -> pandas.DataFrame:
89
+
90
+ r"""웹 수집한 Response 데이터를 Pandas DataFrame 으로 출력
91
+ (str) start : 데이터 수집 시작날짜
92
+ (str) end : 데이터 수집 종료날짜
93
+ (int) gap : 현재로 부터 시작날짜 간격
94
+ (str) code : API 호출을 위한 작업구분 코드
95
+ (int) market: Kospi, Kosdaq 구분자"""
96
+
97
+ # Get Response
98
+ url_data = self._header()
99
+ content = self._json(start=start, end=end, gap=gap, code=code, market=market)
100
+ start, end, json_data = content['start'], content['end'], content['jsonData']
101
+ response = requests.post(url_data['url'], json=json_data, headers=url_data['headers']).json()
102
+ assert len(response['ds1']) != 0, f'{response}' # False 일 때 메세지 출력
103
+
104
+ # Response to DataFrame
105
+ df = pandas.DataFrame(response['ds1'])
106
+ df = self._df_number(df).rename(columns=column)
107
+
108
+ # Case 1 (일간) 데이터
109
+ if '날짜' not in list(df.columns):
110
+ df.insert(0, '날짜', start)
111
+ df['날짜'] = pandas.DatetimeIndex(df['날짜'])
112
+
113
+ # Case 2 (구간) 데이터
114
+ else:
115
+ df['날짜'] = pandas.DatetimeIndex(df['날짜'])
116
+
117
+ # Case 3 (구간) 데이터 : 참여자별 거래내역 구간
118
+ # self.credit_trader()
119
+ if code == "STATSCU0100000150BO":
120
+ if start == end:
121
+ df['날짜'] = f'{start}'
122
+ else:
123
+ df['날짜'] = f'{start}~{end}'
124
+
125
+ # df = df.set_index('날짜')
126
+ return df
@@ -0,0 +1,107 @@
1
+ # 데이터 호출용 파라미터 생성 공용 클래스
2
+ import re
3
+ import numpy
4
+ import pandas
5
+ import datetime
6
+ import requests
7
+ from urllib.parse import urlparse, urlencode
8
+
9
+
10
+ class Header:
11
+ r"""웹사이트 수집을 위한 공용 Header
12
+ - `_now_date()` : 현재 날짜 생성
13
+ - `_date_string()` : 날짜 텍스트 유효성 검사
14
+ - `_df_number()` : thousand Comma 및 `-` 등 공백문자 예외처리"""
15
+
16
+ def _now_date(self):
17
+ r"""Bussiness Day 를 기준으로 `현재일자` 생성"""
18
+ datetime_now = datetime.datetime.now().replace(minute=0, second=0, microsecond=0)
19
+ day_check = datetime_now.weekday() - 4
20
+ if day_check > 0:
21
+ datetime_now = datetime_now - datetime.timedelta(day_check)
22
+ datetime_now = datetime_now.replace(hour=15, minute=30, second=0)
23
+ return datetime_now
24
+
25
+ def _date_string(self, string:str = None):
26
+ r"""`2022-1-2` -> `20220102` 날짜 텍스트 변환기
27
+ string : 날짜 텍스트, 숫자형태 입력도 가능"""
28
+ if string != None:
29
+ string = str(string)
30
+ for punct_string in ['-','/',',']:
31
+ if string.find(punct_string) != -1:
32
+ string = "".join(list(map(lambda x : (f'{x:0>2}'), string.split(punct_string))))
33
+ assert "".join(re.findall('[\d]+', string)) == string, "string 은 숫자만 가능합니다"
34
+ assert len(string) == 8, "ex) 20221112 형태로 다시 입력해 주세요"
35
+ return string
36
+
37
+ def _df_number(self,
38
+ df:pandas.DataFrame=None,
39
+ except_column:list=[],
40
+ except_item:list=[],
41
+ ) -> pandas.DataFrame:
42
+ r"""DataFrame 데이터를, 숫자 데이터 int/float 으로 변경
43
+ (DataFrame) df : 작업할 DataFrame
44
+ (list) except_column : 작업에서 제외할 컬럼
45
+ (list) except_item : NaN 으로 변환할 대상 `ex) '-', '' ..."""
46
+
47
+ token_regex = '^[-]{0,1}[(\d){1,3}]*[.\d]*$'
48
+ number_lambda = lambda x : x == "".join(re.findall(token_regex, x))
49
+ assert df is not None, "변환작업을 진행할 `DataFrame` 이 없습니다."
50
+
51
+ ## Pre Processing
52
+ # 1 object 필드만 대상으로 진행
53
+ column_names = [_ for _ in df.columns if str(df[_].dtype) == 'object' ]
54
+
55
+ # 2 숫자 데이터 정수 또는 실수로 구성된 컬럼 찾기
56
+ column_names = [column for column in column_names
57
+ if len(df[column]) == sum(list(map(number_lambda, df[column]))) # if 정규식을 활용한 컬럼 필터링
58
+ if column not in except_column] # if 사용자 컬럼 필터링
59
+
60
+ # 3 숫자로 구성된 날짜 데이터 컬럼 중 `날짜 데이터` 는 예외 목록으로 추가하기
61
+ # check 1 : 동일한 길이를 갖는가?
62
+ # check 2 : regex 판단시 해당 데이터가 날짜 데이터 형식인가?
63
+ for column in column_names:
64
+ check_items_list = df[column].tolist()
65
+
66
+ # check 1
67
+ items_length = map(lambda x : len(x), list(set(check_items_list)))
68
+ items_length = len(set(list(items_length)))
69
+
70
+ if items_length < 4:
71
+ # check 2
72
+ token_regex_date = '[\d]{2,4}[-./\//]{0,1}[\d]{1,2}[-./\//]{0,1}[\d]{1,2}[-./\//]{0,1}[\d]{1,2}'
73
+ date_check_lambda = lambda x : len("".join(re.findall(token_regex_date, x))) > 0
74
+
75
+ if len(check_items_list) == sum(list(map(date_check_lambda, check_items_list))):
76
+ except_item.append(column)
77
+ column_names = [_ for _ in column_names if _ not in except_item]
78
+
79
+ ## Main Process : float / int 로 변경
80
+ # 필터링 결과 중 numpy.NaN 으로 처리될 데이터 필터링 및 작업
81
+ except_item_list = ['-', '', ' '] + except_item # NaN 으로 변환 적용할 데이터
82
+
83
+ # Removing thousand comma
84
+ # Converting `int` or `float`
85
+ lambda_to_number = lambda x: int(x.replace(',','')) if x.replace(',','').isdigit() \
86
+ else float(x.replace(',','')) if x not in except_item_list else numpy.nan
87
+
88
+ if len(column_names) > 0:
89
+ for column in column_names:
90
+ df[column] = list(map(lambda_to_number, df[column].tolist()))
91
+ return df
92
+
93
+
94
+ def _to_number(self, df:pandas.DataFrame=None, column_list:list=[], except_list:list=[]):
95
+ r"""DataFrame 의 컬럼 숫자로 변경작업 강제로 진행
96
+ (DataFrame) df : 작업을 위한 DataFrame
97
+ (list) column_list : 컬럼명
98
+ (list) except_list : 숫자변환 제외 데이터로 NaN 으로 변경"""
99
+
100
+ except_item_list = ['-', ''] + except_list # NaN 으로 변환 적용할 데이터
101
+ lambda_to_number = lambda x: int(x.replace(',','')) if x.replace(',','').isdigit() \
102
+ else float(x.replace(',','')) if x not in except_item_list else numpy.nan
103
+
104
+ # column list -
105
+ for column in column_list:
106
+ df[column] = list(map(lambda_to_number, df[column].tolist()))
107
+ return df
@@ -0,0 +1,95 @@
1
+ from ._header import *
2
+
3
+
4
+ class KofiaData(HeaderOfKofia):
5
+
6
+ r"""금융투자협회 크롤링 : http://freesis.kofia.or.kr/
7
+ Header(class) 수집을 위한 파라미터 값 모음
8
+ :: 수집을 위한 `연산 메서드` 는 자식 클래스에서 별도로 작업하기
9
+ - `_json()` : Post 수집을 위한 Json Data 생성함수
10
+ - `_get()` : Response to DataFrame 작동함수
11
+
12
+ - `market()` : 증시동향(코스닥, 코스피)
13
+ - `around()` : 증시 주변자금 현황
14
+ - `short()` : 일간 종목별 대차거래 내역
15
+ - `short_balance()`: 신용공여(신용대출) 잔고(공매도) 추이
16
+ - `short_trader()` : 참여자별 대차거래 내역
17
+ """
18
+ # - `credit_deal()` : 신용거래 체결주수 추이
19
+
20
+ def market(self, start:str=None, end:str=None, gap:int=7, market:str='KOSPI'):
21
+ r"""증시동향 : 유가증권, 코스닥 현황"""
22
+ assert market.upper() in ['KOSPI', 'KOSDAQ'], "KOSPI, KOSDAQ 을 입력해 주세요"
23
+ code = {'KOSPI':"STATSCU0100000020BO", 'KOSDAQ':"STATSCU0100000030BO"}[market.upper()]
24
+ column = {"TMPV1":'날짜','TMPV2':f'{market.upper()}지수','TMPV3':'거래량',
25
+ 'TMPV4':'거래대금','TMPV5':'시가총액','TMPV6':'외국인시총','TMPV7':'외국인비중'}
26
+ return self._get(start=start, end=end, gap=gap, code=code, column=column)
27
+
28
+ def around(self, start:str=None, end:str=None, gap:int=7) -> pandas.DataFrame:
29
+ r"""(구간) 증시 주변자금 현황
30
+ (str)start : 시작날짜
31
+ (str)end : 종료날짜
32
+ (int)gap : 날짜 입력이 없는경우 현재로 부터 수집 기준일"""
33
+
34
+ column = {'TMPV1':'날짜', 'TMPV2':'투자자예탁금(파생예수금제외)', 'TMPV3':'파생예수금',
35
+ 'TMPV4':'RP매도잔고', 'TMPV5':'위탁매매미수금', 'TMPV6':'위탁매매미수금대비실제반대금액',
36
+ 'TMPV7':'미수금대비반대매매비중(%)'}
37
+ code = "STATSCU0100000060BO"
38
+ return self._get(start=start, end=end, gap=gap, code=code, column=column)
39
+
40
+ def short(self, date:str=None, market='KOSPI') -> pandas.DataFrame:
41
+ r"""(일간) 종목별 대차거래내역
42
+ (str) date_string : 기준날짜
43
+ (str) market : KOSPI, KOSDAQ"""
44
+
45
+ column = {'TMPV1':'종목명','TMPV2':'종목코드','TMPV3':'체결(주식수)',
46
+ 'TMPV4':'상환(주식수)','TMPV5':'잔고(주식)','TMPV6':'잔고(금액)'}
47
+ code = "STATSCU0100000130BO"
48
+ assert market.upper() in ['KOSPI', 'KOSDAQ'], "KOSPI, KOSDAQ 을 입력해 주세요"
49
+ market = {'KOSPI':1, 'KOSDAQ':2}[market.upper()]
50
+ return self._get(start=date, code=code, column=column, market=market)
51
+
52
+ def short_balance(self, start:str=None, end:str=None, gap:int=7) -> pandas.DataFrame:
53
+ r"""(구간) 신용공여 잔고추이
54
+ (str)start : 시작날짜
55
+ (str)end : 종료날짜
56
+ (int)gap : 날짜 입력이 없는경우 현재로 부터 수집 기준일"""
57
+
58
+ column = {'TMPV1':'날짜', 'TMPV2':'신용융자잔고(전체)', 'TMPV3':'신용융자잔고(KOSPI)',
59
+ 'TMPV4':'신용융자잔고(KOSDAQ)', 'TMPV5':'신용대차잔고(전체)', 'TMPV6':'신용대차잔고(KOSPI)',
60
+ 'TMPV7':'신용대차잔고(KOSDAQ)', 'TMPV8':'청약자금대출', 'TMPV9':'예탁증권담보증권'}
61
+ code = "STATSCU0100000070BO"
62
+ return self._get(start=start, end=end, gap=gap, code=code, column=column)
63
+
64
+
65
+ def short_trader(self, start:str=None, end:str=None, gap:int=7) -> pandas.DataFrame:
66
+ r"""(구간) 신용거래 체결주수
67
+ (str) start : 시작날짜
68
+ (str) end : 종료날짜
69
+ (int) gap : 날짜 입력이 없는경우 현재로 부터 수집 기준일"""
70
+ column = {'TMPV1':'구분','TMPV2':'거래원',
71
+ 'TMPV3':'체결규모(대여)','TMPV4':'비중(대여)','TMPV5':'체결규모(차입)','TMPV6':'비중(차입)'}
72
+ code = "STATSCU0100000150BO"
73
+ df = self._get(start=start, end=end, gap=gap, code=code, column=column)
74
+
75
+ # Post Processing ...
76
+ df['구분'] = list(map(lambda x : numpy.NaN if x in ['',' '] else x, df['구분'].tolist()))
77
+ df['구분'] = df['구분'].fillna(method='ffill')
78
+ return df
79
+
80
+
81
+ # def credit_deal(self, start:str=None, end:str=None, gap:int=7) -> pandas.DataFrame:
82
+ # r"""(구간) 신용거래 체결주수
83
+ # (str) start : 시작날짜
84
+ # (str) end : 종료날짜
85
+ # (int) gap : 날짜 입력이 없는경우 현재로 부터 수집 기준일"""
86
+
87
+ # column = {'TMPV1':'날짜', 'TMPV2':'신용융자거래(전체)', 'TMPV3':'신용융자거래(KOSPI)',
88
+ # 'TMPV4':'신용융자거래(KOSDAQ)', 'TMPV5':'신용대차거래(전체)', 'TMPV6':'신용대차거래(KOSPI)',
89
+ # 'TMPV7':'신용대차거래(KOSDAQ)', 'TMPV8':'청약자금대출', 'TMPV9':'예탁증권담보증권'}
90
+ # code = "STATSCU0100000080BO"
91
+ # df = self._get(start=start, end=end, gap=gap, code=code, column=column)
92
+ # return df.dropna(axis=1, how='all')
93
+
94
+ # class method ...
95
+ kofia = KofiaData()
@@ -0,0 +1 @@
1
+ from .calender import holiday, info
@@ -0,0 +1,6 @@
1
+ import re
2
+ import json
3
+ import pandas
4
+ import datetime
5
+ import requests
6
+ from pytip import FakeAgent, date_to_string