knitr::opts_chunk$set(message = FALSE,
                      warning = FALSE,
                      fig.width = 8, 
                      fig.height = 4.5,
                      fig.align = 'center',
                      out.width='95%', 
                      dpi = 200,
                      cache = T)
# devtools::load_all() # Travis CI fails on load_all()

tidyquant로 한국 주식 하려면 tqk

개요

tidyquanttq_get()으로 한국의 데이터를 가져오는데 제약이 있어 시작했습니다. 우선 code_get()으로 종목 코드를 가져오고, tqk_get()으로 tq_get()과 같은 양식의 데이터를 확보하여 이후 tidyquant의 모든 기능을 한국 데이터로 활용할 수 있습니다.

tidyquant 소개 - 주식 데이터를 tidy하게

tidyquantquantmod 등 주식 분석을 주 목적으로 하는 중요 함수를 제공하는 중요한 패키지입니다. tidy data 개념을 활용한 데이터 핸들링, ggplot과 연계된 강한 차트 그리기, 야후를 기본으로 구글 및 각자 독자적인 데이터 소스로 부터 필요한 데이터를 손쉽게 가져오는 기능, 성능 분석 함수들을 제공하고 있습니다.

주가 지수 가져오기

tidyquant야후 파이넨스에서 정보를 가져옵니다. 가져오는 데이터 소스를 바꾸고 싶으면 어떤 곳에서 가져올지 결정할 수 있는데, tq_get_options()는 가능한 후보를 보여줍니다.

if (!require(tidyquant)) install.packages("tidyquant", repos = "https://cloud.r-project.org/", verbose = F)
library(tidyquant)
tq_get_options()

이때 코스피와 코스닥을 이르는 이름이 각각 ^KS11^KOSDAQ입니다. 각각 한번 가져와 보겠습니다.

tq_get("^KS11")
tq_get("^KOSDAQ")

각 기업의 주가를 가져오려면 종목 번호를 알고 있어야 합니다. 양식은 종목번호.KS입니다. 종목번호는 전자공시시스템에서 사용하는 번호입니다.

삼성전자 번호는 005930 이군요!

ss <- tq_get("005930.KS")
ss

날짜를 지정할 수도 있습니다.

ssdate <- tq_get("005930.KS", from="2016-01-01", to="2016-05-05")
ssdate

배당금 정보는 dividends 에서 확인하시면 됩니다.

ssdiv <- tq_get("005930.KS", get = "dividends")
ssdiv

야후 파이넨스가 데이터 소스이다 보니 모든 정보가 있다고 보기 어렵니다. 거기다 종목 번호를 일일이 찾는 것도 힘들구요. 이런 문제를 해결하기 위해서 tqk가 시작됬습니다.

tqk 소개 - 한국 주식 데이터 패키지

종목 코드 가져오기

본래 tidyquant 패키지는 symbol(ex> 애플사는 AAPL)를 인자로 주식 데이터를 가져옵니다. 한국 주식은 각 종목별로 코드가 있으며 그것 때문에 코드와 종목명이 매치되있는 데이터를 확인할 수 있어야 합니다. tqk 패키지는 code_get()함수를 통해 진행 가능합니다.

if (!require(remotes)) install.packages("remotes", verbose = F)
library(remotes)
if (!require(tqk)) install_github("mrchypark/tqk", verbose = F)
library(tqk)
code<-code_get()
code

주식 데이터 가져오기

tqk_get()은 종목 코드로 데이터를 가져오도록 만들었습니다.

ss_prices <- 
  code_get() %>% 
  filter(grepl("^삼성전자$",name)) %>% 
  select(code) %>% 
  tqk_get(from = "2018-05-01")

ss_prices

데이터는 주요 사이트인 n사, d사, p사 를 모두 대응하는 것을 목표로 하고 있고, 현재 p사(구현 편의성)로 작성되어 있습니다.

Quandl

Quandl은 방대한 양의 경제, 주식에 대한 정보를 가지고 서비스하는 데이터 판매 기업입니다. Quandl이라는 자체 패키지만을 사용해도 되고, tidyquant가 내장하고 있어서 같이 사용해도 됩니다.

tidyverse와 함께 사용하는 시계열 데이터

그 동안의 주식관련 패키지들은 파이프 연산자 %>%와 함꼐 사용하지 못했는데, tidyquant는 그런 문제를 해결하였습니다. 아래 2가지 중요한 함수를 추가함으로써 dplyrtidyr의 함수와 함께 사용할 수 있게 되었습니다.

tq_에서 계산 가능한 함수들

tq_transmute_fun_options() 함수는 각 참고 패키지에서 활용할 수 있는 함수의 리스트를 보여줍니다. 모두 zoo, xts, quantmod, TTR, PerformanceAnalytics의 5개 패키지내의 함수를 지원합니다.

tq_transmute_fun_options() %>% str

zoo 함수

tq_transmute_fun_options()$zoo

xts 함수

tq_transmute_fun_options()$xts

quantmod 함수

tq_transmute_fun_options()$quantmod

TTR 함수

tq_transmute_fun_options()$TTR

PerformanceAnalytics 함수

tq_transmute_fun_options()$PerformanceAnalytics

Return.annualizedReturn.annualized.excess : 기간 반환을 취하여 연간 수익으로 통합합니다. Return.clean : 반환 값에서 특이 값을 제거합니다. Return.excess : 무위험 이자율을 초과하는 수익률로 수익률에서 무위험 이자율을 제거합니다. zerofill : 'NA'값을 0으로 대체하는 데 사용됩니다.

ggplot2와 연계된 차트 그리기

ggplot2 차트를 그리는데 R에서 가장 유명한 패키지 입니다. ggGrammar of Graphics의 줄임말로 그림을 생성하는 것에 대한 규칙을 제안하고 있습니다. tidyquantggplot2에 더해 아래와 같은 기능을 추가로 제공합니다.

살펴보기

tqk_get를 이용해서 사용할 데이터를 가져옵니다. 내장 데이터인 SHANK과 삼성, 네이버를 예시로 사용하겠습니다.

library(tqk)
data(SHANK)

SS <- tqk_get(code[grep("^삼성전자$",code$name),1], to = "2016-12-31")
NVR <- tqk_get(code[grep("^NHN$",code$name),1], to = "2016-12-31")

'end` 매개 변수는 예제 전체에서 날짜 제한을 설정할 때 사용됩니다.

end <- as_date("2016-12-31")

차트 종류

라인 차트

tidyquantgeom_함수를 사용하여 가로 막대형 차트와 촛대형 차트를 시각화하기 전에 단순한 선 차트로 주가를 시각화하여 그래픽 문법을 확인해보겠습니다. 이것은ggplot2 패키지의geom_line을 사용하여 이루어집니다. 주식 데이터로 시작하고 파이프 연산자 (%> %)를 사용하여ggplot ()함수로 보냅니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_line() +
    labs(title = "SamSung Line Chart", y = "Closing Price", x = "") + 
    theme_tq()

바 차트

바 차트는 geom_linegeom_barchart로 바꾸는 걸로 해결됩니다. aes()내의 내용을 의미에 맞게 조정하는 것으로 바 차트를 그리는 것이 끝납니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_barchart(aes(open = open, high = high, low = low, close = close)) +
    labs(title = "SamSung Bar Chart", y = "Closing Price", x = "") + 
    theme_tq()

우리는coord_x_date를 사용하여 특정 섹션을 확대 / 축소합니다.이 섹션에는xlimylim 인수가c (start, end)로 지정되어 차트의 특정 영역에 초점을 맞 춥니 다. xlim의 경우 우리는lubridate를 사용하여 문자 날짜를 날짜 클래스로 변환 한 다음weeks ()함수를 사용하여 6 주를 뺍니다. ylim의 경우 가격을 100에서 120까지 확대합니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_barchart(aes(open = open, high = high, low = low, close = close)) +
    labs(title = "SamSung Bar Chart", 
         subtitle = "Zoomed in using coord_x_date",
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(end - weeks(6), end),
                 ylim = c(1600000, 1800000)) + 
    theme_tq()

색상은color_upcolor_down 인수를 사용하여 수정할 수 있으며size와 같은 매개 변수를 사용하여 모양을 제어 할 수 있습니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_barchart(aes(open = open, high = high, low = low, close = close),
                     color_up = "darkgreen", color_down = "darkred", size = 1) +
    labs(title = "SamSung Bar Chart", 
         subtitle = "Zoomed in, Experimenting with Formatting",
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(end - weeks(6), end),
                 ylim = c(1600000, 1800000)) + 
    theme_tq()

캔들 차트

캔들 차트 또한 바 차트를 그리는 것과 거의 같습니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close)) +
    labs(title = "SamSung Candlestick Chart", y = "Closing Price", x = "") +
    theme_tq()

색상은color_upcolor_down을 사용하여 선 색상을 조절할 수 있고, fill_upfill_down은 사각형을 채 웁니다.

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close),
                        color_up = "darkgreen", color_down = "darkred", 
                        fill_up  = "darkgreen", fill_down  = "darkred") +
    labs(title = "SamSung Candlestick Chart", 
         subtitle = "Zoomed in, Experimenting with Formatting",
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(end - weeks(6), end),
                 ylim = c(1600000, 1800000)) + 
    theme_tq()

여러개의 차트를 그리기

facet_wrap을 사용하여 동시에 여러 주식을 시각화 할 수 있습니다. ggplot ()aes()group을 추가하고ggplot 워크 플로우의 끝에서facet_wrap()함수와 결합함으로써 네 개의 "FANG"주식을 동시에 모두 볼 수 있습니다.

start <- end - weeks(6)
SHANK %>%
    filter(date >= start - days(2 * 15)) %>%
    ggplot(aes(x = date, y = close, group = symbol)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close)) +
    labs(title = "SHANK Candlestick Chart", 
         subtitle = "Experimenting with Mulitple Stocks",
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(start, end)) +
    facet_wrap(~ symbol, ncol = 2, scale = "free_y") + 
    theme_tq()

트랜드 시각화

Moving averages are critical to evaluating time-series trends. tidyquant includes geoms to enable "rapid prototyping" to quickly visualize signals using moving averages and Bollinger bands.

이동 평균

tidyquant에서는 다양한 이동평균 함수를 제공합니다.

이동 평균은geom_ma 함수로 차트에 추가 된 레이어로 적용됩니다. 기하 구조는TTR 패키지에서SMA,EMA,WMA,DEMA,ZLEMA,VWMA,EVWMA와 같은 기본 이동 평균 함수의 래퍼입니다.

Example 1: 50일/200일 단순 이동 평균 차트 작성

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close)) +
    geom_ma(ma_fun = SMA, n = 50, linetype = 5, size = 1.25) +
    geom_ma(ma_fun = SMA, n = 200, color = "red", size = 1.25) + 
    labs(title = "SamSung Candlestick Chart", 
         subtitle = "50 and 200-Day SMA", 
         y = "Closing Price", x = "") + 
         coord_x_date(xlim = c(end - weeks(24), end),
                      ylim = c(1500000, 1850000)) + 
    theme_tq()

Example 2: 지수 이동 평균 차트

SS %>%
    ggplot(aes(x = date, y = close)) +
    geom_barchart(aes(open = open, high = high, low = low, close = close)) +
    geom_ma(ma_fun = EMA, n = 50, wilder = TRUE, linetype = 5, size = 1.25) +
    geom_ma(ma_fun = EMA, n = 200, wilder = TRUE, color = "red", size = 1.25) + 
    labs(title = "SamSung Bar Chart", 
         subtitle = "50 and 200-Day EMA", 
         y = "Closing Price", x = "") + 
         coord_x_date(xlim = c(end - weeks(24), end),
                      ylim = c(1500000, 1850000)) + 
    theme_tq()

볼린저 밴드

[Bollinger Bands] https://en.wikipedia.org/wiki/Bollinger_Bands)는 이동 평균(일반적으로 상하 2SD) 주위의 범위를 플로팅하여 변동성을 시각화하는 데 사용됩니다. 그것들은 이동 평균을 사용하기 때문에,geom_bbands 함수는geom_ma와 거의 동일하게 작동합니다. 동일한 7 개의 이동 평균이 호환됩니다. 가장 큰 차이점은 기본적으로 2 인 표준 편차 인sd 인수와 밴드를 계산하는 데 필요한 'high', 'low'및 'close'를 aes()에 추가하는 것입니다.

Example 1: SMA를 사용하여 BBands 적용

간단한 이동 평균을 사용하여 Bollinger Bands를 추가하는 기본 예제를 살펴 보겠습니다.

SS %>%
    ggplot(aes(x = date, y = close, open = open,
               high = high, low = low, close = close)) +
    geom_candlestick() +
    geom_bbands(ma_fun = SMA, sd = 2, n = 20) +
    labs(title = "SamSung Candlestick Chart", 
         subtitle = "BBands with SMA Applied", 
         y = "Closing Price", x = "") + 
         coord_x_date(xlim = c(end - weeks(24), end),
                      ylim = c(1500000, 1850000)) + 
    theme_tq()

Example 2: Bollinger Bands의 모양 바꾸기

모양은color_ma,color_bands,alpha,fill 인자를 사용하여 수정할 수 있습니다. BBands에 새로운 서식을 적용한 Example 1과 같은 그림이 있습니다.

SS %>%
    ggplot(aes(x = date, y = close, open = open,
               high = high, low = low, close = close)) +
    geom_candlestick() +
    geom_bbands(ma_fun = SMA, sd = 2, n = 20, 
                linetype = 4, size = 1, alpha = 0.2, 
                fill        = palette_light()[[1]], 
                color_bands = palette_light()[[1]], 
                color_ma    = palette_light()[[2]]) +
    labs(title = "SamSung Candlestick Chart", 
         subtitle = "BBands with SMA Applied, Experimenting with Formatting", 
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(end - weeks(24), end),
                 ylim = c(1500000, 1850000)) + 
    theme_tq()

Example 3: 여러 주식에 BBands 추가

start <- end - weeks(12)
SHANK %>%
    filter(date >= start - days(2 * 20)) %>%
    ggplot(aes(x = date, y = close, 
               open = open, high = high, low = low, close = close, 
               group = symbol)) +
    geom_barchart() +
    geom_bbands(ma_fun = SMA, sd = 2, n = 20, linetype = 5) +
    labs(title = "SHANK Bar Chart", 
         subtitle = "BBands with SMA Applied, Experimenting with Multiple Stocks", 
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(start, end)) +
    facet_wrap(~ symbol, ncol = 2, scales = "free_y") + 
    theme_tq()

ggplot2 함수

기본 ggplot2는 재무 데이터를 분석하는데 유용한 많은 기능을 가지고 있습니다. 네이버(NVR)을 사용하여 몇 가지 간단한 예제를 살펴 보겠습니다.

Example 1 : scale_y_log10을 사용한 로그 스케일

ggplot2는 y 축을 로그 스케일로 스케일하기위한scale_y_log10 ()함수를 가지고 있습니다. 이는 분석 할 수있는 선형 추세를 조정하는 경향이 있으므로 매우 유용합니다.

Continuous Scale:

NVR %>%
    ggplot(aes(x = date, y = adjusted)) +
    geom_line(color = palette_light()[[1]]) + 
    scale_y_continuous() +
    labs(title = "Naver Line Chart", 
         subtitle = "Continuous Scale", 
         y = "Closing Price", x = "") + 
    theme_tq()

Log Scale:

NVR %>%
    ggplot(aes(x = date, y = adjusted)) +
    geom_line(color = palette_light()[[1]]) + 
    scale_y_log10() +
    labs(title = "Naver Line Chart", 
         subtitle = "Log Scale", 
         y = "Closing Price", x = "") + 
    theme_tq()

Example 2: geom_smooth로 회귀 추세선

우리는 워크 플로우에geom_smooth ()함수를 빠르게 추가하는 추세선을 적용 할 수 있습니다. 이 함수는 선형(lm)과 loess(loess) 를 포함한 몇 가지 예측 방법을 가지고 있습니다.

Linear:

NVR %>%
    ggplot(aes(x = date, y = adjusted)) +
    geom_line(color = palette_light()[[1]]) + 
    scale_y_log10() +
    geom_smooth(method = "lm") +
    labs(title = "Naver Line Chart", 
         subtitle = "Log Scale, Applying Linear Trendline", 
         y = "Adjusted Closing Price", x = "") + 
    theme_tq()

Example 3: geom_segment로 차트 볼륨

우리는geom_segment ()함수를 사용하여 라인의 시작과 끝을 xy 점으로하는 일일 볼륨을 차트로 표시 할 수 있습니다. aes()를 사용하여 볼륨의 값을 기준으로 색상을 지정하여 이러한 데이터를 강조 표시합니다.

NVR %>%
    ggplot(aes(x = date, y = volume)) +
    geom_segment(aes(xend = date, yend = 0, color = volume)) + 
    geom_smooth(method = "loess", se = FALSE) +
    labs(title = "Naver Volume Chart", 
         subtitle = "Charting Daily Volume", 
         y = "Volume", x = "") +
    theme_tq() +
    theme(legend.position = "none") 

특정 지역을 확대 할 수 있습니다. scale_color_gradient를 사용하여 고점 및 저점을 빠르게 시각화 할 수 있으며geom_smooth를 사용하여 추세를 볼 수 있습니다.

start <- end - weeks(24)
NVR %>%
    filter(date >= start - days(50)) %>%
    ggplot(aes(x = date, y = volume)) +
    geom_segment(aes(xend = date, yend = 0, color = volume)) +
    geom_smooth(method = "loess", se = FALSE) +
    labs(title = "Naver Bar Chart", 
         subtitle = "Charting Daily Volume, Zooming In", 
         y = "Volume", x = "") + 
    coord_x_date(xlim = c(start, end)) +
    scale_color_gradient(low = "red", high = "darkblue") +
    theme_tq() + 
    theme(legend.position = "none") 

테마

tidyquant 패키지는 3 가지 테마로 구성되어있어 신속하게 재무 차트를 조정 할 수 있습니다.

Dark

n_mavg <- 50 # Number of periods (days) for moving average
SHANK %>%
    filter(date >= start - days(2 * n_mavg)) %>%
    ggplot(aes(x = date, y = close, color = symbol)) +
    geom_line(size = 1) +
    geom_ma(n = 15, color = "darkblue", size = 1) + 
    geom_ma(n = n_mavg, color = "red", size = 1) +
    labs(title = "Dark Theme",
         x = "", y = "Closing Price") +
    coord_x_date(xlim = c(start, end)) +
    facet_wrap(~ symbol, scales = "free_y") +
    theme_tq_dark() +
    scale_color_tq(theme = "dark")


Ari1225/tqk documentation built on May 25, 2019, 9:22 a.m.