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
tidyquant의 tq_get()으로 한국의 데이터를 가져오는데 제약이 있어 시작했습니다. 우선 code_get()으로 종목 코드를 가져오고, tqk_get()으로 tq_get()과 같은 양식의 데이터를 확보하여 이후 tidyquant의 모든 기능을 한국 데이터로 활용할 수 있습니다.
tidyquant는 quantmod 등 주식 분석을 주 목적으로 하는 중요 함수를 제공하는 중요한 패키지입니다. 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가 시작됬습니다.
본래 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이라는 자체 패키지만을 사용해도 되고, tidyquant가 내장하고 있어서 같이 사용해도 됩니다.
그 동안의 주식관련 패키지들은 파이프 연산자 %>%와 함꼐 사용하지 못했는데, tidyquant는 그런 문제를 해결하였습니다. 아래 2가지 중요한 함수를 추가함으로써 dplyr과 tidyr의 함수와 함께 사용할 수 있게 되었습니다.
tq_transmute(): 계산된 내용의 컬럼만으로 데이터를 구성합니다.tq_mutate(): 데이터에 계산된 내용의 컬럼을 추가합니다.tq_에서 계산 가능한 함수들tq_transmute_fun_options() 함수는 각 참고 패키지에서 활용할 수 있는 함수의 리스트를 보여줍니다. 모두 zoo, xts, quantmod, TTR, PerformanceAnalytics의 5개 패키지내의 함수를 지원합니다.
tq_transmute_fun_options() %>% str
tq_transmute_fun_options()$zoo
rollapply(data, width, FUN, ..., by = 1, by.column = TRUE, fill = if (na.pad) NA, na.pad = FALSE, partial = FALSE, align = c("center", "left", "right"), coredata = TRUE).rollmax,rollmean,rollmedian,rollsum 등이 있습니다.tq_transmute_fun_options()$xts
기간 적용 기능 :
max, min, mean 등)에 적용합니다.apply.daily (x, FUN, ...).apply.daily,weekly,monthly,quarterly,yearly를 포함합니다.기간 기능 :
to.period (x, period = 'months', k = 1, indexAt, name = NULL, OHLC = TRUE, ...).to.minutes,hourly,daily,weekly,monthly,quarterly,yearly가 포함됩니다.to.period와to.monthly (to.weekly,to.quarterly 등) 양식의 리턴 구조는 다릅니다. to.period는 날짜를 반환하고, to.months는 MON YYYY 문자를 반환합니다. lubridate를 통해 시계열로 작업하고 싶다면to.period를 사용하는 것이 가장 좋습니다.tq_transmute_fun_options()$quantmod
비율 변경 (Delt) 및 Lag 기능
Delt (x1, x2 = NULL, k = 0, type = c ( "arithmetic", "log"))Opcl (OHLC)Lag(x, k = 1)/ Next :Next(x, k = 1)(dplyr :: lag과dplyr :: lead도 사용할 수 있습니다)기간 반환 함수 :
periodReturn (x, period = 'monthly', 부분 집합 = NULL, type = 'arithmetic', leading = TRUE, ...)시리즈 기능 :
seriesHi (x),seriesIncr (x, thresh = 0, diff. = 1L),seriesAccel (x)tq_transmute_fun_options()$TTR
ADX (HLC, n = 14, maType, ...)ROC (x, n = 1, type = c ( "연속", "이산"), na.pad = TRUE): 변화율
운동량 (x, n = 1, na.pad = TRUE): 운동량SMA (x, n = 10, ...): 단순 이동 평균
EMA (x, n = 10, wilder = FALSE, ratio = NULL, ...): 지수 이동 평균ZLEMA (x, n = 10, 비율 = NULL, ...): Zero Lag Exponential Moving Average
VWAP (가격, 물량, n = 10, ...): 물량 가중 평균 가격HMA (x, n = 20, ...): 선체 이동 평균
ALMA (x, n = 9, offset = 0.85, sigma = 6, ...): Arnaud Legoux 이사 평균RSI (가격, n = 14, maType, ...)runSum (x, n = 10, cumulative = FALSE): n- 기간 이동 윈도우에 대한 합계를 반환합니다.
runMin (x, n = 10, cumulative = FALSE): n- 기간 이동 윈도우에 대한 최소값을 반환합니다.
runMax (x, n = 10, cumulative = FALSE): n- 기간 이동 윈도우에 대해 최대 값을 반환합니다.
runMean (x, n = 10, cumulative = FALSE): n-period 이동 윈도우를 의미합니다.
*runMedian (x, n = 10, non.unique = "mean", cumulative = FALSE): n-period 이동 윈도우에 대한 중앙값을 반환합니다.runCov (x, y, n = 10, use = "all.obs", sample = TRUE, 누적 = FALSE): n-period 이동 윈도우에 대한 공분산을 반환합니다.
runCor (x, y, n = 10, use = "all.obs", sample = TRUE, 누적 = FALSE): n-period 이동 윈도우에 대한 상관 관계를 반환합니다.
runVar (x, y = NULL, n = 10, 샘플 = TRUE, 누적 = FALSE): n- 기간 이동 윈도우에 대한 분산을 반환합니다.
runSD (x, n = 10, 샘플 = TRUE, 누적 = FALSE): n- 기간 이동 윈도우에 대한 표준 편차를 반환합니다.
runMAD (x, n = 10, center = NULL, stat = "중간 값", 상수 = 1.4826, non.unique = "평균", cumulative = FALSE)n 기간 이동에 대한 중간 / 평균 절대 편차를 반환합니다. 창문.
wilderSum (x, n = 10): n- 기간 이동 윈도우에 대해 Welles Wilder 스타일 가중치 합계를 되 돌린다.tq_transmute_fun_options()$PerformanceAnalytics
Return.annualized 및Return.annualized.excess : 기간 반환을 취하여 연간 수익으로 통합합니다.
Return.clean : 반환 값에서 특이 값을 제거합니다.
Return.excess : 무위험 이자율을 초과하는 수익률로 수익률에서 무위험 이자율을 제거합니다.
zerofill : 'NA'값을 0으로 대체하는 데 사용됩니다.
ggplot2 차트를 그리는데 R에서 가장 유명한 패키지 입니다. gg는 Grammar of Graphics의 줄임말로 그림을 생성하는 것에 대한 규칙을 제안하고 있습니다. tidyquant는 ggplot2에 더해 아래와 같은 기능을 추가로 제공합니다.
geom_barchart와geom_candlestick을 사용하여 가능합니다.coord 함수 (coord_x_date 및coord_x_datetime)를 사용할 수 있습니다. 이것은 이동 평균 및 Bollinger 밴드 기하학을 사용할 때 중요합니다.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")
geom_barchart을 사용합니다.geom_candlestick을 사용합니다.tidyquant의 geom_함수를 사용하여 가로 막대형 차트와 촛대형 차트를 시각화하기 전에 단순한 선 차트로 주가를 시각화하여 그래픽 문법을 확인해보겠습니다. 이것은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_line를 geom_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를 사용하여 특정 섹션을 확대 / 축소합니다.이 섹션에는xlim 및ylim 인수가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_up 및color_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_up과color_down을 사용하여 선 색상을 조절할 수 있고, fill_up과fill_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와 같은 기본 이동 평균 함수의 래퍼입니다.
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()
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()에 추가하는 것입니다.
간단한 이동 평균을 사용하여 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()
모양은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()
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는 재무 데이터를 분석하는데 유용한 많은 기능을 가지고 있습니다. 네이버(NVR)을 사용하여 몇 가지 간단한 예제를 살펴 보겠습니다.
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()
우리는 워크 플로우에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()
우리는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 가지 테마로 구성되어있어 신속하게 재무 차트를 조정 할 수 있습니다.
theme_tq() + scale_color_tq() + scale_fill_tq()theme_tq_dark() + scale_color_tq(theme = "dark") + scale_fill_tq(theme = "dark")theme_tq_green() + scale_color_tq(theme = "green") + scale_fill_tq(theme = "green")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")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.