0
votes

subset data e.g. all previous year and store as new object.

mtdl <- na.omit(getSymbols("MTDL.JK", auto.assign = F, src = "yahoo", periodicity = "weekly"))

week.year.mtdl <- mtdl %>%
  filter(DATE >= as.Date("2018-01-01") & DATE <= as.Date("2018-12-31"))
2

2 Answers

0
votes

Here are a few ways to go about this if you want to use dplyr.

1 transform xts into data.frame

df_mtdl <- data.frame(date = index(mtdl), coredata(mtdl))
week.year.mtdl <- df_mtdl %>%
  filter(date >= as.Date("2018-01-01") & date <= as.Date("2018-12-31"))

 head(week.year.mtdl)
        date MTDL.JK.Open MTDL.JK.High MTDL.JK.Low MTDL.JK.Close MTDL.JK.Volume MTDL.JK.Adjusted
1 2018-01-01          650          650         620           630          78200         609.6684
2 2018-01-08          630          650         610           610         291800         590.3138
3 2018-01-15          610          750         600           700        9390700         677.4093
4 2018-01-22          700          730         640           700        6816200         677.4093
5 2018-01-29          700          745         685           685         119900         662.8934
6 2018-02-05          695          715         630           635        1533000         614.5070

2 use tidyquant. This returns a tibble instead of an xts object. Tidyquant is built on top of quantmod and a lot of other packages.

library(tidyquant)

tq_mtdl <- tq_get("MTDL.JK", complete_cases = TRUE, periodicity = "weekly")

week.year.mtdl <- tq_mtdl %>%
  filter(date >= as.Date("2018-01-01") & date <= as.Date("2018-12-31"))

head(week.year.mtdl)
# A tibble: 6 x 7
  date        open  high   low close   volume adjusted
  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>
1 2018-01-04   645   645   620   625   137000     605.
2 2018-01-11   620   660   600   645  1460000     624.
3 2018-01-18   645   750   635   660 13683700     639.
4 2018-01-25   680   745   665   685  1359700     663.
5 2018-02-01   700   715   675   700   922200     677.
6 2018-02-08   695   695   630   690   673700     668.
  1. Or use packages timetk (used as part of tidyquant) or tsbox to transform the data from xts to data.frame or tibble.
0
votes

This will give 2018 points of an xts object

mtdl["2018"]

All of these also work:

subset(mtdl, time(.) >= "2018-01-01" & time(.) <= "2018-12-31")

subset(mtdl, start = "2018-01-01", end = "2018-12-31")

window(mtdl, start = "2018-01-01", end = "2018-12-31")

dates <- seq(as.Date("2008-01-01"), as.Date("2008-12-31"), "day")
window(mtdl, dates)

mtdl[dates] # dates is from above

mtdl[ format(time(mtdl), "%Y") == 2018 ]