본문 바로가기

Python Programming/Notes

금융데이터 다루기 - 패키지 설치와 Plotting

금융데이터 다루기

  • 금융데이터를 불러오기 위해 필요한 Library 설치
    • yahoo 에서 제공하는 금융 데이터를 활용할 것이다.
    • yfinance 를 설치한 후 yf라는 이름으로 불러온다.
  • 명칭
    • yahoo finance 사이트에 접속하여 (https://finance.yahoo.com/) 회사 이름을 검색하면 종목에 어떤 명칭을 사용해야 할 지 알 수 있다.
    • 아래 예시로부터, tesla 의 경우 TSLA라는 명칭을 사용하고 있음을 알 수 있다.

!pip install yfinance
import yfinance as yf
Collecting yfinance
  Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz
Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.1.5)
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.19.5)
Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.7/dist-packages (from yfinance) (2.23.0)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance) (0.0.9)
Collecting lxml>=4.5.1
[?25l  Downloading https://files.pythonhosted.org/packages/d2/88/b25778f17e5320c1c58f8c5060fb5b037288e162bd7554c30799e9ea90db/lxml-4.6.2-cp37-cp37m-manylinux1_x86_64.whl (5.5MB)
     |████████████████████████████████| 5.5MB 6.6MB/s 
[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->yfinance) (2018.9)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->yfinance) (2.8.1)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (2.10)
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.20->yfinance) (1.24.3)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (2020.12.5)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24->yfinance) (1.15.0)
Building wheels for collected packages: yfinance
  Building wheel for yfinance (setup.py) ... [?25l[?25hdone
  Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=3d3cbf1923d9d6657f821832ce24529ba8ab6853e32f5b6ff57f6baf45264bd3
  Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c
Successfully built yfinance
Installing collected packages: lxml, yfinance
  Found existing installation: lxml 4.2.6
    Uninstalling lxml-4.2.6:
      Successfully uninstalled lxml-4.2.6
Successfully installed lxml-4.6.2 yfinance-0.1.55

 

tsla 주가 정보 다운로드

import pandas as pd
tsla = yf.download('TSLA')
tsla.head()
[*********************100%***********************]  1 of 1 completed
  Open High Low Close Adj Close Volume
Date            
2010-06-29 3.800 5.000 3.508 4.778 4.778 93831500
2010-06-30 5.158 6.084 4.660 4.766 4.766 85935500
2010-07-01 5.000 5.184 4.054 4.392 4.392 41094000
2010-07-02 4.600 4.620 3.742 3.840 3.840 25699000
2010-07-06 4.000 4.000 3.166 3.222 3.222 34334500

 

Plotting 예시

tesla, 게임 주식, S&P 500, 삼성전자의 Close column을 각각 Plotting 해볼 것이다.

tsla = yf.download('TSLA').Close.plot()
[*********************100%***********************]  1 of 1 completed

gme = yf.download('GME').Close.plot()
[*********************100%***********************]  1 of 1 completed

snp = yf.download("^GSPC").Close.plot()
[*********************100%***********************]  1 of 1 completed

se = yf.download("005930.KS").Close.plot()
[*********************100%***********************]  1 of 1 completed

 

  • 예를 들어, 특정 시점부터의 주가를 확인하고 싶다면, slicing을 활용해 범위를 지정할 수 있다.
  • 예시로 S&P 500의 주가 중 400개의 정보를 불러와 Plotting해 볼 것이다.

 

snp = yf.download("^GSPC")
snp[-400:].Close.plot()
[*********************100%***********************]  1 of 1 completed





<matplotlib.axes._subplots.AxesSubplot at 0x7f2b4fb2ea90>

 

Return 값 구하기

  • dataframe의 각 row는 하루에 해당하는 주가 정보를 가리킨다. (Monday ~ Friday)
  • 해당 정보로부터 각 일자의 return 값을 불러오기 위해 pct_change 함수를 활용할 것이다.
  • return 지표는 해당 종목의 종가에 대한 변동성을 직관적으로 보여준다.삼성 전자(se)의 주가 변동성을 파악해 보자
se = yf.download("005930.KS")
se.head()
[*********************100%***********************]  1 of 1 completed
  Open High Low Close Adj Close Volume
Date            
2000-01-04 6000.0 6110.0 5660.0 6110.0 4761.183105 74195000
2000-01-05 5800.0 6060.0 5520.0 5580.0 4348.184082 74680000
2000-01-06 5750.0 5780.0 5580.0 5620.0 4379.354004 54390000
2000-01-07 5560.0 5670.0 5360.0 5540.0 4317.015625 40305000
2000-01-10 5600.0 5770.0 5580.0 5770.0 4496.240723 46880000
import matplotlib.pyplot as plt
se.Close.pct_change().dropna().plot()
plt.axhline(0.05, ls="--", c='r')
plt.axhline(-0.05, ls="--", c='r')
<matplotlib.lines.Line2D at 0x7f2b4ff37e10>

  • return 의 절대값이 0.05일 때를 나타내기 위해 보조선을 그어 주었다.
  • 이를 통해, 보조건 바깥쪽에 해당하는 시기에 변동성이 크게 나타났음을 알 수 있다.

 

return 값과 주가를 함께 Plotting 하기

  • 우선, ret와 Close 값을 column으로 갖는 dataframe을 생성한다.
df = pd.DataFrame()      # emptry df and assign with column name 
df['Close'] = se.Close
df['ret'] = df.Close.pct_change().dropna()
df.dropna(inplace=True)
df.head()
  Close ret
Date    
2000-01-05 5580.0 -0.086743
2000-01-06 5620.0 0.007168
2000-01-07 5540.0 -0.014235
2000-01-10 5770.0 0.041516
2000-01-11 5770.0 0.000000

 

  • dataframe의 여러 column에 대한 값을 하나의 그래프에 나타내기 위한 코드를 작성한다.
### plotting : pd 

ax = df.Close.plot()
df.ret.plot(secondary_y=True, ax=ax)
plt.title('Samsung Electronics')
Text(0.5, 1.0, 'Samsung Electronics')

 

  • 그렇다면, 최근 코로나19로 인해 높은 변동성을 보였던 게임주식의 경우, 그래프의 형태가 어떻게 나타날까?
gme = yf.download('GME')
gme_df = pd.DataFrame()      # emptry df and assign with column name 
gme_df['Close'] = gme.Close
gme_df['ret'] = gme_df.Close.pct_change().dropna()
gme_df.dropna(inplace=True)

ax = gme_df.Close.plot()
gme_df.ret.plot(secondary_y=True, ax=ax)
plt.title('GAME')
[*********************100%***********************]  1 of 1 completed





Text(0.5, 1.0, 'GAME')

 

APPLE and S&P 500 ?

  • S&P 500 은 미국 증권 거래소에 상장된 500개 대기업의 주가 성과를 측정하는 주식 시장 지수이다, 따라서 시장 전체가 따라가는 가장 일반적인 주가 지수 중 하나이다.
  • statesmodel에서 메소드를 불러와 Apple과 S&P 500 지수의 상관관계를 OLS 를 통해 살펴보고자 한다.

 

aapl = yf.download('AAPL')
snp500 = yf.download('^GSPC')
aapl_ret = aapl.Close.pct_change().dropna()
snp500_ret = snp500.Close.pct_change().dropna()
aapl_ret.head()
[*********************100%***********************]  1 of 1 completed
[*********************100%***********************]  1 of 1 completed





Date
1980-12-15   -0.052171
1980-12-16   -0.073398
1980-12-17    0.024751
1980-12-18    0.028992
1980-12-19    0.061029
Name: Close, dtype: float64
data = pd.DataFrame({'aapl':aapl_ret, 'snp500':snp500_ret}).dropna()
data.head()
  aapl snp500
Date    
1980-12-15 -0.052171 0.001702
1980-12-16 -0.073398 0.008884
1980-12-17 0.024751 0.017534
1980-12-18 0.028992 0.000828
1980-12-19 0.061029 0.005263
from statsmodels.formula.api import ols 
model_fit = ols('aapl~1+snp500', data=data).fit()
print(model_fit.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   aapl   R-squared:                       0.231
Model:                            OLS   Adj. R-squared:                  0.231
Method:                 Least Squares   F-statistic:                     3045.
Date:                Thu, 18 Mar 2021   Prob (F-statistic):               0.00
Time:                        06:57:03   Log-Likelihood:                 22997.
No. Observations:               10149   AIC:                        -4.599e+04
Df Residuals:                   10147   BIC:                        -4.597e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept      0.0006      0.000      2.436      0.015       0.000       0.001
snp500         1.2139      0.022     55.186      0.000       1.171       1.257
==============================================================================
Omnibus:                     2934.527   Durbin-Watson:                   1.915
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           264630.730
Skew:                          -0.380   Prob(JB):                         0.00
Kurtosis:                      28.004   Cond. No.                         88.3
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

'Python Programming > Notes' 카테고리의 다른 글

CRISP-DM 공공자전거 데이터 분석  (2) 2021.04.02
Web_Crawler(3)_HTML  (0) 2021.03.22
Web Crawler(2) - XML 뉴스 정보 가져오기  (0) 2021.02.21
Web Crawler(1) - JSON  (0) 2021.02.14