8 분 소요

주식 데이터 받아오기

주가 데이터를 가져오는 라이브러리들이 있습니다.

  1. finance-datareader

  2. pykrx

  3. pandas_datareader

finance-datareader

!pip install finance-datareader
Collecting finance-datareader
  Downloading finance_datareader-0.9.31-py3-none-any.whl (17 kB)
Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from finance-datareader) (4.2.6)
Requirement already satisfied: requests>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from finance-datareader) (2.23.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from finance-datareader) (4.62.3)
Requirement already satisfied: pandas>=0.19.2 in /usr/local/lib/python3.7/dist-packages (from finance-datareader) (1.3.5)
Collecting requests-file
  Downloading requests_file-1.5.1-py2.py3-none-any.whl (3.7 kB)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19.2->finance-datareader) (2.8.2)
Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19.2->finance-datareader) (2018.9)
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19.2->finance-datareader) (1.21.5)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.19.2->finance-datareader) (1.15.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.3.0->finance-datareader) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.3.0->finance-datareader) (2021.10.8)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.3.0->finance-datareader) (1.24.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.3.0->finance-datareader) (3.0.4)
Installing collected packages: requests-file, finance-datareader
Successfully installed finance-datareader-0.9.31 requests-file-1.5.1
import FinanceDataReader as fdr
import matplotlib.pyplot as plt
import pandas as pd

전체 종목 정보 가져오기

df = fdr.StockListing('KRX')      # 국내 종목
# df = fdr.StockListing('KOSPI')    # KOSPI 종목 
# df = fdr.StockListing('KOSDAQ')   # KOSDAQ 종목
# df = fdr.StockListing('KONEX')    # KONEX 종목

# df = fdr.StockListing('NASDAQ')   # 나스닥 종목
# df = fdr.StockListing('NYSE')     # 뉴욕 증권거래소 종목
# df = fdr.StockListing('AMEX')     # AMEX 종목
# df = fdr.StockListing('SP500')    # S&P500 종목
df
Symbol Market Name Sector Industry ListingDate SettleMonth Representative HomePage Region
0 060310 KOSDAQ 3S 전자부품 제조업 반도체 웨이퍼 캐리어 2002-04-23 03월 김세완 http://www.3sref.com 서울특별시
1 095570 KOSPI AJ네트웍스 산업용 기계 및 장비 임대업 렌탈(파렛트, OA장비, 건설장비) 2015-08-21 12월 박대현 http://www.ajnet.co.kr 서울특별시
2 006840 KOSPI AK홀딩스 기타 금융업 지주사업 1999-08-11 12월 채형석, 이석주(각자 대표이사) http://www.aekyunggroup.co.kr 서울특별시
3 054620 KOSDAQ APS홀딩스 기타 금융업 인터넷 트래픽 솔루션 2001-12-04 12월 정기로 http://www.apsholdings.co.kr 경기도
4 265520 KOSDAQ AP시스템 특수 목적용 기계 제조업 디스플레이 제조 장비 2017-04-07 12월 김영주 http://www.apsystems.co.kr 경기도
... ... ... ... ... ... ... ... ... ... ...
7883 000547 KOSPI 흥국화재2우B NaN NaN NaT NaN NaN NaN NaN
7884 000545 KOSPI 흥국화재우 NaN NaN NaT NaN NaN NaN NaN
7885 003280 KOSPI 흥아해운 해상 운송업 외항화물운송업(케미컬탱커) 1976-06-29 12월 이환구 http://www.heung-a.com 서울특별시
7886 037440 KOSDAQ 희림 건축기술, 엔지니어링 및 관련 기술 서비스업 설계 및 감리용역 2000-02-03 12월 정영균, 이목운, 허철호 (각자대표) http://www.heerim.com 서울특별시
7887 238490 KOSDAQ 힘스 특수 목적용 기계 제조업 OLED Mask 인장기, OLED Mask 검사기 등 2017-07-20 12월 김주환 http://www.hims.co.kr 인천광역시

7888 rows × 10 columns

특정 종목 주가 데이터 가져오기

국내

df = fdr.DataReader(‘종목코드’,’시작일자’,’종료일자’)

해외

df = fdr.DataReader(‘티커’,’시작일자’,’종료일자’)

삼성주식 분석

df = fdr.DataReader('005930','2021-01-01','2022-02-24')   # 삼성전자: 005930
df
Open High Low Close Volume Change
Date
2021-01-04 81000 84400 80200 83000 38655276 0.024691
2021-01-05 81600 83900 81600 83900 35335669 0.010843
2021-01-06 83300 84500 82100 82200 42089013 -0.020262
2021-01-07 82800 84200 82700 82900 32644642 0.008516
2021-01-08 83300 90000 83000 88800 59013307 0.071170
... ... ... ... ... ... ...
2022-02-18 74600 74800 73700 74300 10122226 -0.009333
2022-02-21 73200 74300 72600 74200 10489717 -0.001346
2022-02-22 73000 73400 72800 73400 11692469 -0.010782
2022-02-23 73800 73800 72800 73000 10397964 -0.005450
2022-02-24 72300 72300 71300 71500 15502410 -0.020548

284 rows × 6 columns

plt.figure(figsize=(12, 8))
plt.plot(df['Close'])
plt.show()

캔들 차트 그리기

fdr.chart.plot(df)

pykrx

https://github.com/sharebook-kr/pykrx

KRX, Naver 등의 웹사이트에서 주가정보를 스크래핑하는 모듈

!pip install pykrx
Collecting pykrx
  Downloading pykrx-1.0.32-py3-none-any.whl (92 kB)
[?25l
     |███▌                            | 10 kB 18.0 MB/s eta 0:00:01
     |███████                         | 20 kB 20.7 MB/s eta 0:00:01
     |██████████▋                     | 30 kB 21.6 MB/s eta 0:00:01
     |██████████████▏                 | 40 kB 23.7 MB/s eta 0:00:01
     |█████████████████▊              | 51 kB 20.6 MB/s eta 0:00:01
     |█████████████████████▎          | 61 kB 22.8 MB/s eta 0:00:01
     |████████████████████████▉       | 71 kB 17.7 MB/s eta 0:00:01
     |████████████████████████████▍   | 81 kB 18.4 MB/s eta 0:00:01
     |████████████████████████████████| 92 kB 19.8 MB/s eta 0:00:01
     |████████████████████████████████| 92 kB 412 kB/s 
[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pykrx) (1.3.5)
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from pykrx) (1.21.5)
Collecting datetime
  Downloading DateTime-4.4-py2.py3-none-any.whl (51 kB)
     |████████████████████████████████| 51 kB 383 kB/s 
[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pykrx) (2.23.0)
Requirement already satisfied: xlrd in /usr/local/lib/python3.7/dist-packages (from pykrx) (1.1.0)
Collecting deprecated
  Downloading Deprecated-1.2.13-py2.py3-none-any.whl (9.6 kB)
Collecting zope.interface
  Downloading zope.interface-5.4.0-cp37-cp37m-manylinux2010_x86_64.whl (251 kB)
     |████████████████████████████████| 251 kB 33.4 MB/s 
[?25hRequirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from datetime->pykrx) (2018.9)
Requirement already satisfied: wrapt<2,>=1.10 in /usr/local/lib/python3.7/dist-packages (from deprecated->pykrx) (1.13.3)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pykrx) (2.8.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pykrx) (1.15.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pykrx) (1.24.3)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pykrx) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pykrx) (2021.10.8)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pykrx) (3.0.4)
Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from zope.interface->datetime->pykrx) (57.4.0)
Installing collected packages: zope.interface, deprecated, datetime, pykrx
Successfully installed datetime-4.4 deprecated-1.2.13 pykrx-1.0.32 zope.interface-5.4.0
from pykrx import stock

전체 종목 정보 가져오기

전체 종목 코드: get_market_ticker_list(date=”YYYYMMDD”, market=”거래소명”)

특정 일자 전체 종목 시세: get_market_ohlcv_by_ticker(date=”YYYYMMDD”, market=”거래소명”)

모든 종목의 가격 변동 조회: get_market_price_change_by_ticker(fromdate=”조회시작일”, todate=”조회종료일”, market=”거래소명”)

stock.get_market_ticker_list("20220224")[:6]
['095570', '006840', '027410', '282330', '138930', '001460']
df = stock.get_market_ohlcv_by_ticker(date="20220224")
df
시가 고가 저가 종가 거래량 거래대금 등락률
티커
095570 5450 5450 5260 5300 66711 354912630 -2.93
006840 21400 21400 20500 21000 50468 1055142950 -2.78
027410 5080 5100 5000 5030 65005 327341580 -0.79
282330 161000 165000 159500 161500 21861 3538699500 -0.92
138930 7920 7930 7750 7790 1382061 10816326070 -2.38
... ... ... ... ... ... ... ...
069260 21650 22200 21600 21700 110504 2413462250 -2.03
000540 3690 3700 3580 3585 25472 92364185 -2.85
000547 28450 28450 27150 28400 1555 42868050 -0.18
000545 7880 8000 7790 7890 1985 15529770 0.13
003280 3400 3835 3230 3460 34135710 121297048360 12.70

940 rows × 7 columns

df = stock.get_market_price_change_by_ticker(fromdate="20220222", todate="20220224")
df.head()
종목명 시가 종가 변동폭 등락률 거래량 거래대금
티커
095570 AJ네트웍스 5520 5300 -220 -3.99 147733 794939110
006840 AK홀딩스 22000 21000 -1000 -4.55 172797 3734119550
027410 BGF 5140 5030 -110 -2.14 258600 1311909710
282330 BGF리테일 166000 161500 -4500 -2.71 76115 12401949500
138930 BNK금융지주 8140 7790 -350 -4.30 4009541 31779723550

특정 종목 가져오기

일자별 OHLCV(시가, 고가, 저가, 종가, 거래량) 조회

stock.get_market_ohlcv("20210101", "20220224", "005930")
시가 고가 저가 종가 거래량
날짜
2021-01-04 81000 84400 80200 83000 38655276
2021-01-05 81600 83900 81600 83900 35335669
2021-01-06 83300 84500 82100 82200 42089013
2021-01-07 82800 84200 82700 82900 32644642
2021-01-08 83300 90000 83000 88800 59013307
... ... ... ... ... ...
2022-02-18 74600 74800 73700 74300 10122226
2022-02-21 73200 74300 72600 74200 10489717
2022-02-22 73000 73400 72800 73400 11692469
2022-02-23 73800 73800 72800 73000 10397964
2022-02-24 72300 72300 71300 71500 15502410

284 rows × 5 columns

DIV/BPS/PER/EPS 조회

특정일자의 종목별 DIV/BPS/PER/EPS 조회

ㄴ get_market_fundamental_by_ticker(date=”YYYYMMDD”, market=”거래소명”)

일자별 DIV/BPS/PER/EPS 조회

ㄴ get_market_fundamental_by_date(fromdate, todate, ticker, freq=’d’, name_display=False)

stock.get_market_fundamental_by_ticker(date="20220224", market='KOSPI')
BPS PER PBR EPS DIV DPS
티커
095570 6089 0.000000 0.870117 0 3.960938 210
006840 50471 0.000000 0.419922 0 1.900391 400
027410 15781 17.656250 0.320068 285 2.189453 110
282330 40317 22.734375 4.011719 7103 1.490234 2400
138930 26781 5.199219 0.290039 1498 4.109375 320
... ... ... ... ... ... ...
069260 16351 16.796875 1.330078 1292 4.609375 1000
000540 11107 13.382812 0.320068 268 0.000000 0
000547 0 0.000000 0.000000 0 0.000000 0
000545 0 0.000000 0.000000 0 0.000000 0
003280 0 0.000000 0.000000 0 0.000000 0

913 rows × 6 columns

stock.get_market_fundamental_by_date(fromdate="20220222", todate="20220224", ticker="005930")
BPS PER PBR EPS DIV DPS
날짜
2022-02-22 39406 19.11 1.86 3841 4.08 2994
2022-02-23 39406 19.01 1.85 3841 4.10 2994
2022-02-24 39406 18.61 1.81 3841 4.19 2994

공매도 거래비중 상위 50 종목

get_shorting_trade_top50(“날짜”)

stock.get_shorting_volume_top50("20220223").head()
순위 공매도거래대금 총거래대금 공매도비중 직전40일거래대금평균 공매도거래대금증가율 직전40일공매도평균비중 공매도비중증가율 주가수익률
티커
023530 1 1497378700 4654956200 32.17 1069107545 1.40 14.84 2.17 -0.92
090430 2 14113889500 47737739000 29.57 7608746575 1.85 17.37 1.70 -1.59
008560 3 2890286100 9881029600 29.25 1896946657 1.52 14.34 2.04 -3.34
003240 4 153127000 556363000 27.52 44369800 3.45 5.31 5.19 0.59
003670 5 4384209500 18154011500 24.15 4528691925 0.97 13.98 1.73 0.44

pandas_datareader

!pip install requests_cache
Collecting requests_cache
  Downloading requests_cache-0.9.3-py3-none-any.whl (47 kB)
     |████████████████████████████████| 47 kB 3.8 MB/s 
[?25hCollecting urllib3<2.0.0,>=1.25.5
  Downloading urllib3-1.26.8-py2.py3-none-any.whl (138 kB)
     |████████████████████████████████| 138 kB 27.6 MB/s 
[?25hRequirement already satisfied: appdirs<2.0.0,>=1.4.4 in /usr/local/lib/python3.7/dist-packages (from requests_cache) (1.4.4)
Requirement already satisfied: attrs<22.0,>=21.2 in /usr/local/lib/python3.7/dist-packages (from requests_cache) (21.4.0)
Collecting cattrs<2.0,>=1.8
  Downloading cattrs-1.10.0-py3-none-any.whl (29 kB)
Collecting url-normalize<2.0,>=1.4
  Downloading url_normalize-1.4.3-py2.py3-none-any.whl (6.8 kB)
Requirement already satisfied: requests<3.0,>=2.22 in /usr/local/lib/python3.7/dist-packages (from requests_cache) (2.23.0)
Requirement already satisfied: typing_extensions in /usr/local/lib/python3.7/dist-packages (from cattrs<2.0,>=1.8->requests_cache) (3.10.0.2)
Collecting urllib3<2.0.0,>=1.25.5
  Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)
     |████████████████████████████████| 127 kB 27.0 MB/s 
[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0,>=2.22->requests_cache) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0,>=2.22->requests_cache) (2021.10.8)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3.0,>=2.22->requests_cache) (3.0.4)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from url-normalize<2.0,>=1.4->requests_cache) (1.15.0)
Installing collected packages: urllib3, url-normalize, cattrs, requests-cache
  Attempting uninstall: urllib3
    Found existing installation: urllib3 1.24.3
    Uninstalling urllib3-1.24.3:
      Successfully uninstalled urllib3-1.24.3
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.
Successfully installed cattrs-1.10.0 requests-cache-0.9.3 url-normalize-1.4.3 urllib3-1.25.11
import pandas_datareader as pdr
import requests_cache

코스피 코스닥 지수 가져오기

pdr.DataReader(‘종목’, ‘yahoo’, start, end)

session = requests_cache.CachedSession(cache_name='cache', backend='sqlite')
# just add headers to your session and provide it to the reader
session.headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0', 'Accept': 'application/json;charset=utf-8'}

kospi = pdr.DataReader('^KS11','yahoo', "20210101", "20220224", session=session)
kospi
High Low Open Close Volume Adj Close
Date
2021-01-04 2946.540039 2869.110107 2874.500000 2944.449951 1026500 2944.449951
2021-01-05 2990.570068 2921.840088 2943.669922 2990.570068 1519900 2990.570068
2021-01-06 3027.159912 2961.370117 2993.340088 2968.209961 1793400 2968.209961
2021-01-07 3055.280029 2980.750000 2980.750000 3031.679932 1524700 3031.679932
2021-01-08 3161.110107 3040.110107 3040.110107 3152.179932 1297900 3152.179932
... ... ... ... ... ... ...
2022-02-18 2747.080078 2711.879883 2714.520020 2744.520020 512900 2744.520020
2022-02-21 2746.620117 2694.899902 2706.649902 2743.800049 495000 2743.800049
2022-02-22 2721.840088 2690.090088 2705.080078 2706.790039 648100 2706.790039
2022-02-23 2729.560059 2705.310059 2727.429932 2719.530029 537700 2719.530029
2022-02-24 2694.550049 2642.629883 2689.280029 2648.800049 903880 2648.800049

283 rows × 6 columns

plt.figure(figsize=(12, 8))
plt.plot(kospi['Close'])
plt.show()
WARNING:matplotlib.font_manager:findfont: Font family ['Malgun Gothic'] not found. Falling back to DejaVu Sans.

fdr.chart.plot(kospi)

카테고리:

업데이트:

댓글남기기