개미들을 위한 퀀트 자동 매매 프로그램 개발자 블로그입니다. 프로그래밍과 퀀트 투자를 합니다.

방구석퀀트

네이버카페 : 방구석 퀀트 놀러오세요^^ https://cafe.naver.com/conerquant 가입해 주세요.

2020년 11월 30일 월요일

R을 이용한 RSI 일주일, 2주일, 한달 지표 일봉에 같이 그리기

카톡으로 회원님께서 RSI 높은순위로 정렬할 때,

일주일 기준, 한달 기준으로도 정렬할 수 있냐고 질문 주셨는데 그 때는 저도 RSI 이해가 없어서 제대로 답변을 못 드렸었네요 ^^;


RSI 산출하는 함수에서 n=14 가 기본으로 셋팅되어 있는데요.

이 n 값을 5로 주면 지난 5일간의 추세강도를 계산하게 되고,

n 값을 20으로 주게 되면 지난 20일간의 추세강도가 계산되게 됩니다.


하여 RSI 높은순위로 정렬하는 백테스트 코드에서 이 N 값을 변경해서 원하는 기준기간을 셋팅하면 됩니다.


참고로 기준기간 n 값을 바꾸게 되면 RSI 값이 어떻게 변하는지 아래 챠트를 보겠습니다.



n 값, 즉 평가기간이 짧아질수록 RSI 값 변동폭이 커지고, 평가기간이 길어질수록 변동폭이 좁아지는 것을 알 수 있습니다.


만약 매매전략 매수조건에 RSI 값이 30 이하에서 이상으로 변경될 때 라고 가정한다면 위 챠트에서 2019년 12월 4일(Dec 4, 2019)에 RSI 기준기간이 5일(일주일)로 셋팅되어 있었다면 매수가 되는 반면, 나머지 기준기간 2주일(10일), 한달(20일)로 셋팅되어 있는 RSI값은 매수조건을 만족하지 못했습니다.


위 챠트를 그리는 소스코드는 아래와 같습니다.




# plotly 챠트
library(plotly)
library(quantmod)
samsung <- getSymbols('005930.KS', auto.assign = FALSE)
colnames(samsung) <- c('open','high','low','close','volume','adjusted')
#samsung$rtn <- ROC(Cl(samsung)) #일일 수익률
samsung <- na.omit(samsung) # NA 제거
# basic example of ohlc charts
df <- data.frame(Date=index(samsung),coredata(samsung))
df <- tail(df, 600)
# cutom colors
i <- list(line = list(color = 'red'))
d <- list(line = list(color = 'blue'))
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~open, close = ~close,
high = ~high, low = ~low,
increasing = i, decreasing = d)
fig <- fig %>% add_lines(x = ~Date, y = ~close,
line = list(color = 'black', width = 2), inherit = F)
fig <- fig %>% layout(title = "Basic Candlestick Chart",
xaxis = list(rangeslider = list(visible = F)),
showlegend = FALSE)
fig
# RSI 추가
df <- data.frame(Date=index(samsung),coredata(samsung))
df$rsi_week <- RSI(df$close,n=5)
df$rsi_2weeks <- RSI(df$close,n=10)
df$rsi_month <- RSI(df$close,n=20)
df <- tail(df, 600)
i <- list(line = list(color = 'red'))
d <- list(line = list(color = 'blue'))
fig <- df %>% plot_ly(x = ~Date, type="candlestick", name = "일봉",
open = ~open, close = ~close,
high = ~high, low = ~low,
increasing = i, decreasing = d)
fig <- fig %>% add_lines(x = ~Date, y = ~rsi_week , name = "RSI_일주일",
line = list(color = 'green', width = 1),
inherit = F, yaxis = "y2")
fig <- fig %>% add_lines(x = ~Date, y = ~rsi_2weeks , name = "RSI_2주일",
line = list(color = 'orange', width = 1),
inherit = F, yaxis = "y2")
fig <- fig %>% add_lines(x = ~Date, y = ~rsi_month , name = "RSI_한달",
line = list(color = 'blue', width = 1),
inherit = F, yaxis = "y2")
fig <- fig %>% add_lines(x = ~Date, y = ~close, name='종가',
line = list(color = 'black', width = 2), inherit = F)
fig <- fig %>% layout(title = "Basic Candlestick Chart",
xaxis = list(rangeslider = list(visible = F)),
showlegend = TRUE,
yaxis2 = list(
tickfont = list(color = "green"),
overlaying = "y",
side = "right",
title = "rsi"
))
fig



댓글 없음:

댓글 쓰기

가장 많이 본 글