Metadata-Version: 2.1
Name: pykis
Version: 0.7.0
Summary: A python wrapper for open trading api of Korea Investment & Securities.
Project-URL: Github, https://github.com/pjueon/pykis
Project-URL: Bug Tracker, https://github.com/pjueon/pykis/issues
Author-email: Jueon Park <bluegbgb@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2022 Jueon Park
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.7
Requires-Dist: pandas>=1.4
Requires-Dist: requests>=2.25.1
Description-Content-Type: text/markdown

# pykis
- pykis는 한국투자증권에서 제공하는 Open Trading API를 쉽게 사용하기 위한 **비공식** python wrapper입니다. 
- 기존 eFriend expert (HTS 프로그램) 연동 방식 API 대비 다음과 같은 장점들이 있습니다. 
  - Web API 방식 사용 
  - 별도의 HTS 프로그램에 의존하지 않음
  - 사용 가능 환경(OS)에 제한이 없음

- 기존 eFriend expert 연동 방식 API를 사용하는 python 패키지는 [pjueon/eFriendPy](https://github.com/pjueon/eFriendPy)를 참고하세요.


## 사용전 유의사항 
### license 관련
pykis는 Apache-2.0 license를 따릅니다. 
- Apache-2.0 license에서 규정하는 조건 안에서 자유롭게 수정/재배포/사용이 가능합니다. 자세한 사항은 [LICENSE](LICENSE)를 참고 바랍니다.
- pykis의 동작에는 불완전한 부분이나 버그가 있을 수 있습니다. 또한 pykis의 API는 언제든 변경될 수 있습니다.
- pykis의 제작자([pjueon](https://github.com/pjueon))는 이 코드에 대해서 어떤 것도 보장하지 않습니다. 코드 사용중 생긴 **어떠한 종류의 피해(ex> 버그, 사용자의 실수, 투자로 인한 손실 등)에 대해서도 책임지지 않습니다.**

### KIS Developers 서비스 신청
- pykis를 사용하기 위해서는 한국투자증권 홈페이지에서 KIS Developers 서비스 신청을 통해 API key를 발급받아야 합니다.
- KIS Developers 서비스 신청방법은 한국투자증권의 [공식 wikidocs](https://wikidocs.net/159333)를 참고하세요.

### 기타
- pykis는 개인 투자 용도로만 개발되었습니다. 
- pykis를 사용하기 위해서는 python 3.7 버전 이상이 필요합니다.
- pykis는 아직 개발 단계입니다. 버그나 기능 요청 등의 feedback은 issue나 pull request를 통해 부탁드립니다. 

## 패키지 설치 
- pykis는 현재 개발 단계로 수정이 잦습니다. git을 통해 해당 repository를 clone하여 사용하세요.  
```shell
git clone https://github.com/pjueon/pykis.git
cd pykis
pip3 install -r requirements.txt
```
- 추후 pip 를 통해 설치할 수 있도록 정식 패키징 예정입니다. 


## API 기본 사용법 
### 패키지 import 
```python
import pykis
```

### `Api` 객체 생성
실제 계좌를 사용하는 경우
```python
# API 사용을 위한 API key정보 및 계좌 정보를 설정합니다. 
# 별도의 파일(json, yaml, xml, etc) 등에 내용을 저장하여 불러오는 것을 추천합니다. 
# key 정보는 절대 외부로 유출되지 않도록 주의하시고, 유출시 즉시 재발급 하시기 바랍니다.  

key_info = {		# KIS Developers 서비스 신청을 통해 발급받은 API key 정보
	"appkey": "[발급 받은 APP Key]",                  
	"appsecret": "[발급 받은 APP Secret]" 
}

account_info = {	# 사용할 계좌 정보
	"account_code": "[API를 신청한 종합 계좌번호(계좌번호 앞자리 8자리 숫자)]",   
	"product_code": "[계좌번호의 끝자리 2자리 숫자]"             # ex> "01", "22", etc
}

# API 객체 생성 
api = pykis.Api(key_info=key_info, account_info=account_info)
```

모의 계좌를 사용하는 경우 
```python
domain = pykis.DomainInfo(kind="virtual")


# API 객체 생성 
api = pykis.Api(key_info=key_info, domain_info=domain_info, account_info=account_info)
```

### 사용 계좌 변경
```python
account_info = {    # 사용할 계좌 정보
	"account_code": "[API를 신청한 종합 계좌번호(계좌번호 앞자리 8자리 숫자)]",   
	"product_code": "[계좌번호의 끝자리 2자리 숫자]"             # ex> "01", "22", etc
}

api.set_account(account_info)
```

### 거래 가능 현금 조회
```python
cash = api.get_kr_buyable_cash()
print(f"거래 가능 현금: {cash} 원")
```

### 국내 주식 현재가 조회
```python
ticker = "005930"   # 삼성전자 종목코드
price = api.get_kr_current_price(ticker)
print(f"삼성전자 현재가: {price} 원")
```

### 국내 주식 최근 가격 조회 (일/주/월 OHLCV)
```python
# 최근 30 일/주/월 OHLCV 데이터를 DataFrame으로 반환
ticker = "005930"   # 삼성전자 종목코드
time_unit = "D"     # 기간 분류 코드 (D/day-일, W/week-주, M/month-월), 기본값 "D"
ohlcv = api.get_kr_ohlcv(ticker, time_unit)
```

### 국내 주식 하한가 조회
```python
ticker = "005930"   # 삼성전자 종목코드
price = api.get_kr_min_price(ticker)
print(f"삼성전자 하한가: {price} 원")
```

### 국내 주식 상한가 조회
```python
ticker = "005930"   # 삼성전자 종목코드
price = api.get_kr_max_price(ticker)
print(f"삼성전자 상한가: {price} 원")
```

### 국내 주식 잔고 조회 
```python
# DataFrame 형태로 국내 주식 잔고 반환 
stock = api.get_kr_stock_balance()
print(f"보유중인 국내 주식: \n{stock}")
```

### 국내 주식 총 예수금 조회 
```python
deposit = api.get_kr_deposit()
print(f"총 예수금: {deposit} 원")
```

### 국내 주식 매수 주문
```python
ticker = "005930"   # 삼성전자 종목코드
price = 100000      # 매수 가격 예시. 가격이 0 이하인 경우 시장가로 매수

# 종목코드 ticker인 국내 주식 1주 매수 주문 
ret = api.buy_kr_stock(ticker, 1, price=price)

# 반환값: 서버 응답 (주문 번호 등의 정보)
print(ret)
```

### 국내 주식 매도 주문 
```python
ticker = "005930"   # 삼성전자 종목코드
price = 100000      # 매도 가격 예시. 가격이 0 이하인 경우 시장가로 매도

# 종목코드 ticker인 국내 주식 1주를 지정가로 매도 주문 
ret = api.sell_kr_stock(ticker, 1, price=price)

# 반환값: 서버 응답 (주문 번호 등의 정보)
print(ret)
```

### 정정/취소 가능한 국내 주식 주문 조회
```python
# 정정/취소 가능한 국내 주식 주문을 DataFrame으로 반환
orders = api.get_kr_orders()
print(orders)
```

### 미체결 국내 주식 주문 취소
```python
# order_num: 주문 번호. api.get_kr_orders 통해 확인 가능.
# amount: 취소할 주문 수량. 지정하지 않은 경우 잔량 전부 취소.
api.cancel_kr_order(order_num, amount)
```

### 모든 미체결 국내 주식 주문 취소
```python
api.cancel_all_kr_orders()
```

### 국내 주식 주문 정정
```python
# order_num: 주문 번호. api.get_kr_orders 통해 확인 가능.
# price: 정정할 1주당 가격.
# amount: 정정할 주문 수량. 지정하지 않은 경우 잔량 전부 정정.
api.revise_kr_order(order_num, price, amount)
```


## 관련 참고 자료
- [한국투자증권 KIS Developers](https://apiportal.koreainvestment.com)
- [한국투자증권 Open Trading API Github](https://github.com/koreainvestment/open-trading-api)
- [한국투자증권 Wikidocs](https://wikidocs.net/profile/info/book/13688)
