R에서 금융 데이터 가져오기와 관리
Joshua Ulrich
Quantitative Analyst & quantmod Co-Author and Maintainer

xts 인덱스는 UTC 기준 1970-01-01 자정 이후 초 단위merge()는 내부 인덱스를 사용함merge() 결과는 첫 번째 객체의 시간대를 가짐datetime <- as.POSIXct("2017-01-18 10:00:00", tz = "UTC")
london <- xts(1, datetime, tzone = "Europe/London")
tokyo <- xts(1, datetime, tzone = "Asia/Tokyo")
merge(london, tokyo)
london tokyo
2017-01-18 10:00:00 1 1
merge(tokyo, london)
tokyo london
2017-01-18 19:00:00 1 1
head(dc_trades)
Price
2016-01-16 08:00:58 20.85
2016-01-16 08:01:56 20.85
2016-01-16 08:03:35 20.85
2016-01-16 08:07:44 20.84
2016-01-16 08:45:58 20.85
2016-01-16 08:46:49 20.85
datetimes <- seq(from = as.POSIXct("2016-01-16 08:00"),
to = as.POSIXct("2016-01-17 18:00"),
by = "1 min")
regular_xts <- xts(, order.by = datetimes)
merged_xts <- merge(dc_trades, regular_xts)
head(merged_xts)
Price
2016-01-16 08:00:00 NA
2016-01-16 08:00:58 20.85
2016-01-16 08:01:00 NA
2016-01-16 08:01:56 20.85
2016-01-16 08:02:00 NA
2016-01-16 08:03:00 NA
# 모든 관측치는 NA여야 함
all(is.na(merged_xts["2016-01-16 19:00/2016-01-17 07:00"]))
TRUE
# xts 시각별 서브셋팅
merged_trade_day <- merged_xts["T08:00/T18:00"]
# 이제 관측치가 없음
nrow(merged_trade_day["2016-01-16 19:00/2016-01-17 07:00"])
0
split()-lapply()-rbind() 패턴# split()으로 겹치지 않는 청크 목록으로 분할
trade_day_list <- split(merged_trade_day, "days")
# 각 청크에 lapply()로 함수 적용
filled_trade_day_list <- lapply(trade_day_list, na.locf)
# do.call()과 rbind()로 청크 목록 결합
filled_trade_day <- do.call(rbind, filled_trade_day_list)
to.period()로 촘촘한 장중 데이터를 집계period: 새 주기(초, 시, 일 등)k: 새 관측치당 주기 수head(dc_price)
DC.Price
2016-01-16 00:00:07 20.84224
2016-01-16 00:00:08 20.84225
2016-01-16 00:00:08 20.84225
2016-01-16 00:00:11 20.84225
2016-01-16 00:00:25 20.84224
2016-01-16 00:00:44 20.84224
xts_5min <- to.period(dc_price, period = "minutes", k = 5)
head(xts_5min, n = 4)
dc_price.Open dc_price.High dc_price.Low dc_price.Close
2016-01-16 00:03:49 20.84224 20.84227 20.84140 20.84160
2016-01-16 00:09:50 20.84160 20.84160 20.84156 20.84156
2016-01-16 00:14:57 20.84156 20.84156 20.84154 20.84154
2016-01-16 00:19:23 20.84154 20.84154 20.83206 20.83211
xts_aligned <- align.time(xts_5min, n = 60 * 5)
head(xts_aligned, n = 4)
dc_price.Open dc_price.High dc_price.Low dc_price.Close
2016-01-16 00:05:00 20.84224 20.84227 20.84140 20.84160
2016-01-16 00:05:00 20.84160 20.84160 20.84156 20.84156
2016-01-16 00:15:00 20.84156 20.84156 20.84154 20.84154
2016-01-16 00:20:00 20.84154 20.84154 20.83206 20.83211
R에서 금융 데이터 가져오기와 관리