Exercises 2.1, 2.2, 2.3, 2.4, 2.5 and 2.8 from the Hyndman online Forecasting book.
Use the help function to explore what the series gafa_stock, PBS, vic_elec and pelt represent.
library("fma")
library("xts")
library("ggplot2")
library("forecast")
library("fpp3")
library('lubridate')
library('tsibble')
library('readr')
library('readxl')
help(gafa_stock)
help(PBS)
help(vic_elec)
help(pelt)
autoplot(gafa_stock) + ggtitle("Historical stock prices from 2014-2018") + xlab("Year") + ylab("Price")
autoplot(vic_elec) + ggtitle("Half-hourly electricity demand for Victoria, Australia") + xlab("Year") + ylab("Demand")
autoplot(pelt) + ggtitle("Pelt trading records") + xlab("Year") + ylab("Records")
### 2 Use filter() to find what days corresponded to the peak closing
price for each of the four stocks in gafa_stock.
gafa_stock %>% select(Symbol,Date,Close) %>% group_by(Symbol) %>% filter(Close == max(Close))
## # A tsibble: 4 x 3 [!]
## # Key: Symbol [4]
## # Groups: Symbol [4]
## Symbol Date Close
## <chr> <date> <dbl>
## 1 AAPL 2018-10-03 232.
## 2 AMZN 2018-09-04 2040.
## 3 FB 2018-07-25 218.
## 4 GOOG 2018-07-26 1268.
Download the file tute1.csv
tute1 <- readr::read_csv("tute1.csv")
head(tute1)
## # A tibble: 6 × 4
## Quarter Sales AdBudget GDP
## <date> <dbl> <dbl> <dbl>
## 1 1981-03-01 1020. 659. 252.
## 2 1981-06-01 889. 589 291.
## 3 1981-09-01 795 512. 291.
## 4 1981-12-01 1004. 614. 292.
## 5 1982-03-01 1058. 647. 279.
## 6 1982-06-01 944. 602 254
mytimeseries <- tute1 |>
mutate(Quarter = yearquarter(Quarter)) |>
as_tsibble(index = Quarter)
mytimeseries |>
pivot_longer(-Quarter) |>
ggplot(aes(x = Quarter, y = value, colour = name)) +
geom_line() +
facet_grid(name ~ ., scales = "free_y")
Without facet_grid().
mytimeseries |>
pivot_longer(-Quarter) |>
ggplot(aes(x = Quarter, y = value, colour = name)) +
geom_line()
### 4 The USgas package contains data on the demand for natural gas in
the US.
library('USgas')
tsibbleOfUsTotal = as_tsibble(us_total, key = state, index=year)
head(tsibbleOfUsTotal)
## # A tsibble: 6 x 3 [1Y]
## # Key: state [1]
## year state y
## <int> <chr> <int>
## 1 1997 Alabama 324158
## 2 1998 Alabama 329134
## 3 1999 Alabama 337270
## 4 2000 Alabama 353614
## 5 2001 Alabama 332693
## 6 2002 Alabama 379343
gasConsumptionNewEngland = tsibbleOfUsTotal %>% filter( state %in% c('Maine', 'Vermont', 'New Hampshire', 'Massachusetts', 'Connecticut', 'Rhode Island'))
autoplot(as.ts(as.ts(gasConsumptionNewEngland)))
### 8 Monthly Australian retail data is provided in aus_retail. Select
one of the time series as follows (but choose your own seed value):
set.seed(12345678)
myseries <- aus_retail |>
filter(`Series ID` == sample(aus_retail$`Series ID`,1))
autoplot(as.ts(myseries %>% select(Month,Turnover)))
feasts::gg_season(myseries %>% select(Month,Turnover))