#003 pykrx 주식정보 활용(1) : Python, PostgreSQL
지난 포스팅에 pykrx 주식 종목정보를 가져와서 테이블에 저장하는 파이썬 프로그램을 소개했다.
pykrx를 가져오는 방법, 라이브러리 설치 등은 지난 포스팅을 참고하기 바란다.
2023.03.20 - [IT/파이썬 실전 (Python)] - #002 pykrx 주식 종목 정보 가져오기 : Python, PostgreSQL
#002 pykrx 주식 종목 정보 가져오기 : Python, PostgreSQL
#002 pykrx 주식 종목 정보 가져오기 : Python, postgreSQL 이번 포스팅은 파이썬으로 pykrx 라이브러리를 통해 주식 종목 정보를 가져와서 db에 저장하는 내용이다. 지난 포스팅에 키움 api 연결을 위해 파
doitsql.tistory.com
애초에 출발점은 외인, 기관이 매집하는 종목을 찾는 것이었다. 증권사에서 제공하는 정보에 외인 순매수상위, 기관 순매수 상위 등을 볼 수 있는 화면이 있지만 순매수 금액이라는 절대수치를 기준으로 하기 때문에 시총이 적은 종목은 나오기 힘든 구조이다. 또, 외인+기관의 합을 알고 싶은데 제공하지 않는다.
이에 시총대비 차지비율 순으로 볼 수 있는 것을 만들어 보려고 시작했다. pykrx에서 제공하는 정보를 가져와서 테이블에 저장하고 sql로 입맛에 맞는 정보를 찾아보는 것이 주목적이다.
파이썬으로 실질적인 무언가를 해보고 싶어 할 분들을 위해 참고 및 학습 목적으로 활용되길 바란다.
물론 테이블을 구축하고 배치 프로그램으로 데이터를 매일 적재한다면 주식투자에 도움이 될 수 있는 정보이기도 하다.
지금부터 테이블과 데이터를 적재할 배치 프로그램을 공개한다.
pykrx 정보별 저장 테이블
pykrx에서 가져오는 정보와 저장할 테이블을 간략히 나열해 본다
1) 종목정보 stock.get_market_ticker_list → ticker
종목정보는 ticker 테이블에 저장한다.
krx 정보에 market 구분이 없어서 자료를 가져올 때 'KOSPI', 'KOSDAQ', 'KONEX'로 나누어 3번 가져와서 INSERT 한다.
뒤에 공개할 프로그램 소스를 보면 이해할 것이다.
2) 시세정보 stock.get_market_ohlcv → price
시세정보는 price 테이블에 저장한다.
일자별로 종목의 시세를 저장한다.
3) 펀더멘탈 정보 stock.get_market_fundamental → fundamental
펀더멘탈 정보는 fundamental 테이블에 저장한다.
4) 투자자별 거래대금 정보 stock.get_market_trading_value_by_date → trading_value
투자자별 거래대금 정보는 trading_value 테이블에 저장한다.
5) 투자자별 거래량 정보 stock.get_market_trading_volume_by_date → trading_volume
투자자별 거래량 정보는 trading_volume 테이블에 저장한다.
6) 투자자별 순매수 정보 stock.get_market_net_purchases_of_equities→ net_purchase
투자자별 순매수 정보는 net_purchase 테이블에 저장한다.
krx에서 제공하는 정보가 전체를 한 번에 제공하는 것이 아니라 투자자별로 제공하여서 insert후에 열을 update 하는 구조로 되어있다. 추후에 나올 파이썬 소스를 보면 이해할 것이다.
이로 인해 주기적으로 vacuum 작업이 필요하게 되었다.
vacuum 작업에 대해서는 별도로 포스팅에서 말씀드리려고 한다.
7) 시가총액 정보 stock.get_market_cap → market_cap
시가총액 정보는 market_cap 테이블에 저장한다.
8) 외국인보유 정보 stock.get_exhaustion_rates_of_foreign_investment → foreign_share
외국인보유 정보는 foreign_share테이블에 저장한다.
이상 8개의 테이블이다.
각 테이블들의 세부정보는 다음에 나올 테이블 crate 문을 참고 바란다.
pykrx에서 설명하는 자료를 같이 참조 바란다.
선행되어야 하는 조건
포스팅의 실 사용을 위해서는
1. PostgreSQl 설치
2. db 생성
3. 아나콘다 설치
4. 파이참 설치
5. pykrx 라이브러리 설치
가 선행되어 있어야 한다.
이전 포스팅을 참고하기 바란다.
2022.12.10 - [IT/SQL 기초강좌 (PostgreSQL)] - 3강 SQL이 뭐지? 도구들을 설치해보자. ( PostgreSQL, HeidiSQL )
3강 SQL이 뭐지? 도구들을 설치해보자. ( PostgreSQL, HeidiSQL )
1. PostgreSQL 설치 ( Windows10 64bit 기준) 2. HeidiSQL 설치 3. 실습용 데이터 설치 순으로 진행하겠습니다. 지난 시간까지 SQL이 뭔지 대충 감을 잡는 시간을 가졌습니다. 이번 시간에는 본격적인 SQL을 공
doitsql.tistory.com
2023.02.15 - [IT/파이썬 기초 (Python)] - #005 파이썬 기초 : 실습환경 아나콘다 설치
#005 파이썬 기초 : 실습환경 아나콘다 설치
파이썬기초강의강좌, Python기초강의강좌, Anaconda설치 파이썬 기초 : 실습환경 아나콘다 설치 파이썬은 https://www.python.org/downloads/ Download Python The official home of the Python Programming Language www.python.org 에
doitsql.tistory.com
2023.02.17 - [IT/파이썬 기초 (Python)] - #007 파이썬 개발환경 : 파이참(PyCharm) 설치
#007 파이썬 개발환경 : 파이참(PyCharm) 설치
Python기초강의강좌, 파이썬기초강의강좌 파이썬 개발환경 : 파이참(PyCharm) 설치 통합 개발 환경(IDE) 중 하나인 PyCharm은 JetBrains에서 제작했으며 현재 사용되는 파이썬 개발툴 중 가장 많이 알려진
doitsql.tistory.com
2023.03.20 - [IT/파이썬 실전 (Python)] - #002 pykrx 주식 종목 정보 가져오기 : Python, PostgreSQL
#002 pykrx 주식 종목 정보 가져오기 : Python, PostgreSQL
#002 pykrx 주식 종목 정보 가져오기 : Python, postgreSQL 이번 포스팅은 파이썬으로 pykrx 라이브러리를 통해 주식 종목 정보를 가져와서 db에 저장하는 내용이다. 지난 포스팅에 키움 api 연결을 위해 파
doitsql.tistory.com
테이블 create 문
파일로 올려 드릴 수도 있으나 내려받는 것은 항상 찝찝해하시는 분이 많아서 sql을 코드블록으로 올린다.
-- 종목코드
create table if not exists public.ticker
(
ticker char(6) primary key,
ticker_name varchar(50) not null,
market varchar(10) not null,
last_update timestamp(6) default now() not null
);
create index idx_ticker_ticker_name
on public.ticker (ticker_name);
comment on table public.ticker is '종목정보';
comment on column public.ticker.ticker is '종목';
comment on column public.ticker.ticker_name is '종목명';
comment on column public.ticker.market is '시장구분';
comment on column public.ticker.last_update is '최종수정일';
-- 시세정보
create table if not exists public.price
(
ticker char(6) not null,
std_date date not null,
open bigint not null,
high bigint not null,
low bigint not null,
close bigint not null,
volume bigint not null,
trans_p bigint not null,
f_rate real not null,
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index price_std_date
on public.price (std_date, ticker);
comment on table public.price is '시세정보';
comment on column public.price.ticker is '종목';
comment on column public.price.std_date is '기준일자';
comment on column public.price.open is '시가';
comment on column public.price.high is '고가';
comment on column public.price.low is '저가';
comment on column public.price.close is '종가';
comment on column public.price.volume is '거래량';
comment on column public.price.trans_p is '거래대금';
comment on column public.price.f_rate is '등락률';
comment on column public.price.last_update is '최종수정일';
-- 펀더멘탈
create table if not exists public.fundamental
(
ticker char(6) not null,
std_date date not null,
bps bigint not null,
per real not null,
pbr real not null,
eps bigint not null,
div real not null,
dps bigint not null,
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index fundamental_std_date
on public.fundamental (std_date, ticker);
comment on table public.fundamental is '펀더멘탈';
comment on column public.fundamental.ticker is '종목';
comment on column public.fundamental.std_date is '기준일자';
comment on column public.fundamental.bps is '주당순자산가치';
comment on column public.fundamental.per is '주가수익비율';
comment on column public.fundamental.pbr is '주가순자산비율';
comment on column public.fundamental.eps is '주당순이익';
comment on column public.fundamental.div is '배당수익율';
comment on column public.fundamental.dps is '주당배당금';
comment on column public.fundamental.last_update is '최종수정일';
-- 투자자별 거래대금
create table if not exists public.trading_value
(
ticker char(6) not null,
std_date date not null,
finv bigint not null, -- 금융투자
insu bigint not null, -- 보험
invt bigint not null, -- 투신
pbon bigint not null, -- 사모
bank bigint not null, -- 은행
etcf bigint not null, -- 기타금융
pens bigint not null, -- 연기금
orgt bigint not null, -- 기관계
ecor bigint not null, -- 기타법인
pers bigint not null, -- 개인
fore bigint not null, -- 외국인
efor bigint not null, -- 기타외국인
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index trading_value_std_date
on public.trading_value (std_date, ticker);
comment on table public.trading_value is '투자자별 거래대금';
comment on column public.trading_value.ticker is '종목';
comment on column public.trading_value.std_date is '기준일자';
comment on column public.trading_value.finv is '금융투자';
comment on column public.trading_value.insu is '보험';
comment on column public.trading_value.invt is '투신';
comment on column public.trading_value.pbon is '사모';
comment on column public.trading_value.bank is '은행';
comment on column public.trading_value.etcf is '기타금융';
comment on column public.trading_value.pens is '연기금';
comment on column public.trading_value.orgt is '기관계';
comment on column public.trading_value.ecor is '기타법인';
comment on column public.trading_value.pers is '개인';
comment on column public.trading_value.fore is '외국인';
comment on column public.trading_value.efor is '기타외국인';
comment on column public.trading_value.last_update is '최종수정일';
-- 투자자별 거래량
create table if not exists public.trading_volume
(
ticker char(6) not null,
std_date date not null,
finv bigint not null, -- 금융투자
insu bigint not null, -- 보험
invt bigint not null, -- 투신
pbon bigint not null, -- 사모
bank bigint not null, -- 은행
etcf bigint not null, -- 기타금융
pens bigint not null, -- 연기금
orgt bigint not null, -- 기관계
ecor bigint not null, -- 기타법인
pers bigint not null, -- 개인
fore bigint not null, -- 외국인
efor bigint not null, -- 기타외국인
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index trading_volume_std_date
on public.trading_volume (std_date, ticker);
comment on table public.trading_volume is '투자자별 거래량';
comment on column public.trading_volume.ticker is '종목';
comment on column public.trading_volume.std_date is '기준일자';
comment on column public.trading_volume.finv is '금융투자';
comment on column public.trading_volume.insu is '보험';
comment on column public.trading_volume.invt is '투신';
comment on column public.trading_volume.pbon is '사모';
comment on column public.trading_volume.bank is '은행';
comment on column public.trading_volume.etcf is '기타금융';
comment on column public.trading_volume.pens is '연기금';
comment on column public.trading_volume.orgt is '기관계';
comment on column public.trading_volume.ecor is '기타법인';
comment on column public.trading_volume.pers is '개인';
comment on column public.trading_volume.fore is '외국인';
comment on column public.trading_volume.efor is '기타외국인';
comment on column public.trading_volume.last_update is '최종수정일';
-- 투자자별 순매수
create table if not exists public.net_purchase
(
ticker char(6) not null,
std_date date not null,
finv_v bigint default 0 not null, -- 금융투자 거래량
finv_m bigint default 0 not null, -- 금융투자 거래금액
insu_v bigint default 0 not null, -- 보험
insu_m bigint default 0 not null, -- 보험
invt_v bigint default 0 not null, -- 투신
invt_m bigint default 0 not null, -- 투신
pbon_v bigint default 0 not null, -- 사모
pbon_m bigint default 0 not null, -- 사모
bank_v bigint default 0 not null, -- 은행
bank_m bigint default 0 not null, -- 은행
etcf_v bigint default 0 not null, -- 기타금융
etcf_m bigint default 0 not null, -- 기타금융
pens_v bigint default 0 not null, -- 연기금
pens_m bigint default 0 not null, -- 연기금
orgt_v bigint default 0 not null, -- 기관계
orgt_m bigint default 0 not null, -- 기관계
ecor_v bigint default 0 not null, -- 기타법인
ecor_m bigint default 0 not null, -- 기타법인
pers_v bigint default 0 not null, -- 개인
pers_m bigint default 0 not null, -- 개인
fore_v bigint default 0 not null, -- 외국인
fore_m bigint default 0 not null, -- 외국인
efor_v bigint default 0 not null, -- 기타외국인
efor_m bigint default 0 not null, -- 기타외국인
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index net_purchase_std_date
on public.net_purchase (std_date, ticker);
comment on table public.net_purchase is '투자자별 순매수';
comment on column public.net_purchase.ticker is '종목';
comment on column public.net_purchase.std_date is '기준일자';
comment on column public.net_purchase.finv_v is '금융투자 거래량';
comment on column public.net_purchase.insu_v is '보험 거래량';
comment on column public.net_purchase.invt_v is '투신 거래량';
comment on column public.net_purchase.pbon_v is '사모 거래량';
comment on column public.net_purchase.bank_v is '은행 거래량';
comment on column public.net_purchase.etcf_v is '기타금융 거래량';
comment on column public.net_purchase.pens_v is '연기금 거래량';
comment on column public.net_purchase.orgt_v is '기관계 거래량';
comment on column public.net_purchase.ecor_v is '기타법인 거래량';
comment on column public.net_purchase.pers_v is '개인 거래량';
comment on column public.net_purchase.fore_v is '외국인 거래량';
comment on column public.net_purchase.efor_v is '기타외국인 거래량';
comment on column public.net_purchase.finv_m is '금융투자 거래금액';
comment on column public.net_purchase.insu_m is '보험 거래금액';
comment on column public.net_purchase.invt_m is '투신 거래금액';
comment on column public.net_purchase.pbon_m is '사모 거래금액';
comment on column public.net_purchase.bank_m is '은행 거래금액';
comment on column public.net_purchase.etcf_m is '기타금융 거래금액';
comment on column public.net_purchase.pens_m is '연기금 거래금액';
comment on column public.net_purchase.orgt_m is '기관계 거래금액';
comment on column public.net_purchase.ecor_m is '기타법인 거래금액';
comment on column public.net_purchase.pers_m is '개인 거래금액';
comment on column public.net_purchase.fore_m is '외국인 거래금액';
comment on column public.net_purchase.efor_m is '기타외국인 거래금액';
comment on column public.net_purchase.last_update is '최종수정일';
-- 시가총액 market_cap
create table if not exists public.market_cap
(
ticker char(6) not null,
std_date date not null,
close bigint default 0 not null, -- 종가
cap bigint default 0 not null, -- 시가총액
qty bigint default 0 not null, -- 거래량
tran bigint default 0 not null, -- 거래대금
s_qty bigint default 0 not null, -- 상장주식수
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index market_cap_std_date
on public.market_cap (std_date, ticker);
comment on table public.market_cap is '시가총액';
comment on column public.market_cap.ticker is '종목';
comment on column public.market_cap.std_date is '기준일자';
comment on column public.market_cap.close is '종가';
comment on column public.market_cap.cap is '시가총액';
comment on column public.market_cap.qty is '거래량';
comment on column public.market_cap.tran is '거래대금';
comment on column public.market_cap.s_qty is '상장주식수';
comment on column public.market_cap.last_update is '최종수정일';
-- 외국인보유 foreign_share
create table if not exists public.foreign_share
(
ticker char(6) not null,
std_date date not null,
s_qty bigint default 0 not null, -- 상장주식수
qty bigint default 0 not null, -- 보유수량
s_ratio real default 0.0 not null, -- 지분율
l_qty bigint default 0 not null, -- 한도수량
l_ratio real default 0.0 not null, -- 한도소진률
last_update timestamp(6) default now() not null,
primary key (ticker, std_date)
);
create index foreign_share_std_date
on public.foreign_share (std_date, ticker);
comment on table public.foreign_share is '외국인보유';
comment on column public.foreign_share.ticker is '종목';
comment on column public.foreign_share.std_date is '기준일자';
comment on column public.foreign_share.s_qty is '상장주식수';
comment on column public.foreign_share.qty is '보유수량';
comment on column public.foreign_share.s_ratio is '지분율';
comment on column public.foreign_share.l_qty is '한도수량';
comment on column public.foreign_share.l_ratio is '한도소진률';
comment on column public.foreign_share.last_update is '최종수정일';
이제 생성된 테이블에 데이터를 적재할 파이썬 프로그램에 대해서는 다음 포스팅에 계속~~
감사합니다.
Do it! SQL을 찾아 주셔서 감사합니다. ♥ 댓글이 큰 힘이 됩니다. |
'IT > 파이썬 실전 (Python)' 카테고리의 다른 글
#004 pykrx 주식정보 활용(2) : Python, PostgreSQL (98) | 2023.03.26 |
---|---|
#002 pykrx 주식 종목 정보 가져오기 : Python, PostgreSQL (130) | 2023.03.20 |
#001 키움 API 환경 - 아나콘다 32bit 가상환경 만들기 (40) | 2023.03.18 |
댓글