-
[금융경제] 주가데이터 지수화(Indexing), 변동률 구하기, 주가데이터 불러오기__Data Analysis/교육 2021. 5. 18. 02:18
주식 데이터를 불러오는 방법
1. yfinance
2. pykrx의 stock
3. FinanceDataReader
4. pandas_datareader의 data
아래의 글에서 자세히 설명했으니 참고해주세요!
[Python] - [python] jupyter+colab | 파이썬에서 금융데이터 수집하기
[python] jupyter+colab | 파이썬에서 금융데이터 수집하기
목표 : 유가 증권 시장의 데이터를 끌어올 수 있다. 금융데이터를 수집하는 라이브러리 4가지 종류 - pykrx - FinanceDataReader - pandas_datareader - yfinance Jupyter 또는 Pycharm에서 라이브러리 설치 방법..
kkwor1d.tistory.com
아래 코드에서는 yfinance와 pykrx를 이용해 금융 데이터를 수집하고 분석하는 방법을 소개합니다.
그 외 FinanceDataReader 또는 pandas datareader는 다른 글에서 소개하도록 하겠습니다.
< 코드 구현 >
필요한 패키지 설치!pip install yfinance !pip install pykrx
라이브러리 불러오기
import pandas as pd import numpy as np import matplotlib.pyplot as plt import FinanceDataReader as fdr from pandas_datareader import data as pdr import yfinance as yf import pykrx as krx from pykrx import stock # pykrx:패키지, import stock:모듈
yahoo financial API¶
pandas-datareader의 yahoo API를 이용해 금융데이터 수집하기df_ss = pdr.get_data_yahoo('005930.KS','20200101','20200131') df_apl = pdr.get_data_yahoo('AAPL','20200101','20200131')
df_ss.head() # ohlcv : Open High Low Close Volume
Out>High Low Open Close Volume Adj Close Date 2020-01-02 56000 55000 55500 55200 12993228 52537.179688 2020-01-03 56600 54900 56000 55500 15422255 52822.707031 2020-01-06 55600 54600 54900 55500 10278951 52822.707031 2020-01-07 56400 55600 55700 55800 10009778 53108.238281 2020-01-08 57400 55900 56200 56800 23501171 54059.992188 불필요한 컬럼 삭제df_ss.drop('Adj Close',axis=1, inplace=True) df_apl.drop('Adj Close',axis=1, inplace=True)
df_ss.info() # 연월일 index로 잡혀있음.
>
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 20 entries, 2020-01-02 to 2020-01-31 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 High 20 non-null int64 1 Low 20 non-null int64 2 Open 20 non-null int64 3 Close 20 non-null int64 4 Volume 20 non-null int64 dtypes: int64(5) memory usage: 960.0 bytes
df_ss.head()
Out>High Low Open Close Volume Date 2020-01-02 56000 55000 55500 55200 12993228 2020-01-03 56600 54900 56000 55500 15422255 2020-01-06 55600 54600 54900 55500 10278951 2020-01-07 56400 55600 55700 55800 10009778 2020-01-08 57400 55900 56200 56800 23501171 삼성전자 & 애플 주가 비교# 단위가 달라 비교 불가 --- 지수화 필요 plt.plot(df_ss.index,'Close',data=df_ss,label='SAMSUNG') plt.plot(df_apl.index,'Close',data=df_apl,label='APPLE') plt.xticks(rotation=45) plt.grid() plt.legend() plt.title('SAMSUNG VS APPLE') plt.show()
일간변동률 지수화(indexing)¶
- 가격이 다른 두 주가의 수익률 비교
- 오늘 - 전일(특정일) / 전일 * 100
변동률 계산# 변동률 for df in [df_ss,df_apl]: df['전일종가'] = df['Close'].shift() # default 1 : 하루(1일) 차분, 아래로 내려라 ; diff df['전일대비변동가격'] = df['Close'] - df['전일종가'] df['전일기준등락율'] = ((df['Close'] - df['전일종가'])/df['전일종가']) * 100 # 주식의 1년은 365일이 아니다. 즉, 1주일도 7일이 아닌 5일을 계산해야 한다.(빨간날,주말 제외)
df_ss.head()
Out>High Low Open Close Volume 전일종가 전일대비변동가격 전일기준등락율 Date 2020-01-02 56000 55000 55500 55200 12993228 NaN NaN NaN 2020-01-03 56600 54900 56000 55500 15422255 55200.0 300.0 0.543478 2020-01-06 55600 54600 54900 55500 10278951 55500.0 0.0 0.000000 2020-01-07 56400 55600 55700 55800 10009778 55500.0 300.0 0.540541 2020-01-08 57400 55900 56200 56800 23501171 55800.0 1000.0 1.792115 df_apl.head()
Out>High Low Open Close Volume 전일종가 전일대비변동가격 전일기준등락율 Date 2019-12-31 73.419998 72.379997 72.482498 73.412498 100805600 NaN NaN NaN 2020-01-02 75.150002 73.797501 74.059998 75.087502 135480400 73.412498 1.675003 2.281632 2020-01-03 75.144997 74.125000 74.287498 74.357498 146322800 75.087502 -0.730003 -0.972204 2020-01-06 74.989998 73.187500 73.447502 74.949997 118387200 74.357498 0.592499 0.796825 2020-01-07 75.224998 74.370003 74.959999 74.597504 108872000 74.949997 -0.352493 -0.470305 차트 출력plt.plot(df_ss.index,'전일기준등락율',data=df_ss,label='SAMSUNG') plt.plot(df_apl.index,'전일기준등락율',data=df_apl,label='APPLE') plt.xticks(rotation=45) plt.grid() plt.legend() plt.title('SAMSUNG VS APPLE') plt.show()
Pykrx¶
Pykrx의 stock을 이용해 주식 데이터 수집하기
df_ss = stock.get_market_ohlcv_by_date('20190101','20210101', '005930') df_lg = stock.get_market_ohlcv_by_date('20190101','20210101', '066570')
df_ss.head()
Out>시가 고가 저가 종가 거래량 날짜 2019-01-02 39400 39400 38550 38750 7847664 2019-01-03 38300 38550 37450 37600 12471493 2019-01-04 37450 37600 36850 37450 14108958 2019-01-07 38000 38900 37800 38750 12748997 2019-01-08 38000 39200 37950 38100 12756554 for df in [df_ss,df_lg]: df['전일종가'] = df['종가'].shift() df['일일등락률'] = ((df['종가'] - df['전일종가'])/df['전일종가']) * 100
df_ss.head()
Out[36]:시가 고가 저가 종가 거래량 전일종가 일일등락률 날짜 2019-01-02 39400 39400 38550 38750 7847664 NaN NaN 2019-01-03 38300 38550 37450 37600 12471493 38750.0 -2.967742 2019-01-04 37450 37600 36850 37450 14108958 37600.0 -0.398936 2019-01-07 38000 38900 37800 38750 12748997 37450.0 3.471295 2019-01-08 38000 39200 37950 38100 12756554 38750.0 -1.677419 df_lg.head()
Out>시가 고가 저가 종가 거래량 전일종가 일일등락률 날짜 2019-01-02 63300 64200 62700 62800 568844 NaN NaN 2019-01-03 63100 64100 62100 62900 604561 62800.0 0.159236 2019-01-04 63000 63400 61100 62200 602100 62900.0 -1.112878 2019-01-07 63100 64700 62700 64200 660173 62200.0 3.215434 2019-01-08 63700 63700 61200 61900 1338626 64200.0 -3.582555 # shift 후 결측값 채우는 방법 # 방법1 : df_lg.fillna(0, inplace=True, axis=1) # 방법2 : 앞뒤로 채워넣음. 0일리는 없음. 새로 발행되었으면 모를까 for df in [df_ss,df_lg]: df['일일등락률'].fillna(method='ffill',inplace=True) # 헷갈리면 위아래 다 열엉 df['일일등락률'].fillna(method='bfill',inplace=True) # 또는 df_lg.fillna 만해도 채워짐
plt.plot(df_ss.index,'일일등락률',data=df_ss,label='SAMSUNG') plt.plot(df_lg.index,'일일등락률',data=df_lg,label='LG') plt.xticks(rotation=45) plt.grid() plt.legend() plt.title('SAMSUNG VS LG') plt.show()
변화를 확인하려면 누적값을 봐야함df_ss['일일등락률'].cumsum()[:5]
Out>날짜 2019-01-02 -2.967742 2019-01-03 -5.935484 2019-01-04 -6.334420 2019-01-07 -2.863125 2019-01-08 -4.540544 Name: 일일등락률, dtype: float64
plt.plot(df_ss.index,df_ss['일일등락률'].cumsum(),label='SAMSUNG') plt.plot(df_lg.index,df_lg['일일등락률'].cumsum(),label='LG') plt.xticks(rotation=45) plt.grid() plt.legend() plt.title('SAMSUNG VS LG') plt.show()
type(df_ss)
Out>pandas.core.frame.DataFrame
df_lg.info()
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 494 entries, 2019-01-02 to 2020-12-30 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 시가 494 non-null int32 1 고가 494 non-null int32 2 저가 494 non-null int32 3 종가 494 non-null int32 4 거래량 494 non-null int32 5 전일종가 493 non-null float64 6 일일등락률 494 non-null float64 dtypes: float64(2), int32(5) memory usage: 21.2 KB
df_ss.shape # 거래소 운영일만 데이터 있음.
Out>(494, 7)
이동평균선
# 이동평균선 rolling (series 데이터 사용) window_size = 250 # 1년 단위로 묶는다 df_ss['종가'].rolling(window_size, min_periods=1).max() # min_periods : 하루라도 있으면 묶어라
Out>날짜 2019-01-02 38750.0 2019-01-03 38750.0 2019-01-04 38750.0 2019-01-07 38750.0 2019-01-08 38750.0 ... 2020-12-23 73900.0 2020-12-24 77800.0 2020-12-28 78700.0 2020-12-29 78700.0 2020-12-30 81000.0 Name: 종가, Length: 494, dtype: float64
temp = pd.DataFrame({"SS":df_ss['종가'], "LG":df_lg['종가']}) temp.head()
Out>SS LG 날짜 2019-01-02 38750 62800 2019-01-03 37600 62900 2019-01-04 37450 62200 2019-01-07 38750 64200 2019-01-08 38100 61900 temp.corr() # 60이면 상관도가 높은편 -- LG가 오르면 SS도 오른다? # -- 양의 관계는 같이 구매하면 안되지. 하나 폭락하면 같이 떨어짐
Out>SS LG SS 1.000000 0.595367 LG 0.595367 1.000000 plt.scatter(temp.SS,temp.LG) plt.xlabel('SS') plt.ylabel('LG') plt.show()
from scipy import stats reg = stats.linregress(temp.SS,temp.LG)
print(type(reg)) print(reg) # reg = ('d'=value) # 키워드 dict
<class 'scipy.stats._stats_mstats_common.LinregressResult'> LinregressResult(slope=0.9480898106012626, intercept=22915.262833912013, rvalue=0.5953667255560411, pvalue=1.0476300600213361e-48, stderr=0.057682414451396484, intercept_stderr=3026.2527009378027)
# y = ax + b 회귀선 x= 1 hx = reg.slope * x + reg.intercept # reg[0]*x + reg[1]
plt.scatter(temp.SS,temp.LG) plt.scatter(temp.SS,reg.slope * temp.SS + reg.intercept) plt.xlabel('SS') plt.ylabel('LG') plt.show()
728x90'__Data Analysis > 교육' 카테고리의 다른 글
[금융경제] 유가증권 - 수익률 계산 (0) 2021.06.08 [금융경제] 파생상품 - 옵션(Option) (0) 2021.05.31 [금융경제] 파생상품 - 선물(Futures) (0) 2021.05.29 [금융경제] 실습2 - 환율 (0) 2021.05.26 [금융경제] 실습1 - 국채권과 금리 이상현상 확인 (0) 2021.05.15