2.10 Exercises (2.1, 2.2, 2.3, 2.4, 2.5 & 2.8)

library(fpp3)
## Warning: package 'fpp3' was built under R version 3.6.3
## -- Attaching packages ---------------------------------------- fpp3 0.4.0 --
## v tibble      3.1.0     v tsibble     1.0.1
## v dplyr       1.0.5     v tsibbledata 0.3.0
## v tidyr       1.1.3     v feasts      0.2.2
## v lubridate   1.7.4     v fable       0.3.1
## v ggplot2     3.3.5
## Warning: package 'tibble' was built under R version 3.6.3
## Warning: package 'tidyr' was built under R version 3.6.3
## Warning: package 'tsibble' was built under R version 3.6.3
## Warning: package 'tsibbledata' was built under R version 3.6.3
## Warning: package 'fabletools' was built under R version 3.6.3
## -- Conflicts --------------------------------------------- fpp3_conflicts --
## x lubridate::date()       masks base::date()
## x dplyr::filter()         masks stats::filter()
## x tsibble::intersect()    masks base::intersect()
## x tsibble::interval()     masks lubridate::interval()
## x dplyr::lag()            masks stats::lag()
## x tsibble::new_interval() masks lubridate::new_interval()
## x tsibble::setdiff()      masks base::setdiff()
## x tsibble::union()        masks base::union()

2.1

Use the help function to explore what the series gafa_stock, PBS, vic_elec and pelt represent.

?gafa_stock
## starting httpd help server ... done
?PBS
?vic_elec
?pelt
  1. Use autoplot() to plot some of the series in these data sets.
autoplot(gafa_stock)
## Plot variable not specified, automatically selected `.vars = Open`

Per the textbook, performed the steps to easily plot PBS. When originally using the autoplot function on PBS, too many variables caused issues and the graphs did not print.

By filtering and selecting specific columns we can create a cleaner plot that shows the time intervals.

PBS %>% 
    filter(ATC2 == "A10") %>%
    select(Month, Concession, Type, Cost) %>%
    summarise(TotalC = sum(Cost)) %>%
    mutate(Cost = TotalC/1e6)-> demoplot

autoplot(demoplot)
## Plot variable not specified, automatically selected `.vars = TotalC`

autoplot(vic_elec)
## Plot variable not specified, automatically selected `.vars = Demand`

autoplot(pelt)
## Plot variable not specified, automatically selected `.vars = Hare`

What is the time interval of each series?

Gafa_Stock

Gafa_Stock has a daily time interval from 2014 to 2018.

PBS

PBS has a monthly time interval

Vic_Elec

Vic_Elec has a 30 minute time interval that spans from 2012 to 2015.

Pelt

Pelet has a yearly time interval.

2.2

Use filter() to find what days corresponded to the peak closing price for each of the four stocks in gafa_stock.

gafa_stock %>%
    group_by(Symbol) %>%
    filter(Close == max(Close)) %>%
    select(Symbol, Date, 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.

2.3

Download the file tute1.csv from the book website, open it in Excel (or some other spreadsheet application), and review its contents. You should find four columns of information. Columns B through D each contain a quarterly series, labelled Sales, AdBudget and GDP. Sales contains the quarterly sales for a small company over the period 1981-2005. AdBudget is the advertising budget and GDP is the gross domestic product. All series have been adjusted for inflation.

a.You can read the data into R with the following script:

tute1 <- readr::read_csv("tute1.csv")
## Parsed with column specification:
## cols(
##   Quarter = col_date(format = ""),
##   Sales = col_double(),
##   AdBudget = col_double(),
##   GDP = col_double()
## )
View(tute1)
  1. Convert the data to time series
mytimeseries <- tute1 %>%
  mutate(Quarter = yearmonth(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()

Without the facet_grid, the data is harder to distinguish and read.

2.4

The USgas package contains data on the demand for natural gas in the US.

A. Install the USgas package.

library(USgas)

B. Create a tsibble from us_total with year as the index and state as the key.

gas1 <- us_total %>% as_tsibble(index=year, key=state)
View(gas1)

C. Plot the annual natural gas consumption by state for the New England area (comprising the states of Maine, Vermont, New Hampshire, Massachusetts, Connecticut and Rhode Island).

gas1 %>%
    filter(state %in% c("Maine", "Vermont", "New Hampshire", "Massachusetts", "Connecticut", "Rhode Island")) %>%
    autoplot(y/1e3) +
    labs(y = "million cubic feet")

2.5

  1. Download tourism.xlsx from the book website and read it into R using readxl::read_excel().
tourism <- readxl::read_excel("tourism.xlsx")
  1. Create a tsibble which is identical to the tourism tsibble from the tsibble package.
tourism1 <- tourism %>% mutate(Quarter = yearquarter(Quarter)) %>% as_tsibble(key=c("Region", "State", "Purpose"), index="Quarter")
  1. Find what combination of Region and Purpose had the maximum number of overnight trips on average.
tourism %>%
    group_by(Region, Purpose) %>%
    summarise(mean = mean(Trips)) %>%
    ungroup() %>%
    filter(mean == max(mean))
## `summarise()` has grouped output by 'Region'. You can override using the `.groups` argument.
## # A tibble: 1 x 3
##   Region Purpose   mean
##   <chr>  <chr>    <dbl>
## 1 Sydney Visiting  747.
  1. Create a new tsibble which combines the Purposes and Regions, and just has total trips by State.
tourism %>% group_by(State) %>% summarise(total=sum(Trips))
## # A tibble: 8 x 2
##   State                total
##   <chr>                <dbl>
## 1 ACT                 41007.
## 2 New South Wales    557367.
## 3 Northern Territory  28614.
## 4 Queensland         386643.
## 5 South Australia    118151.
## 6 Tasmania            54137.
## 7 Victoria           390463.
## 8 Western Australia  147820.

2.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(128)
myseries <- aus_retail %>%
  filter(`Series ID` == sample(aus_retail$`Series ID`,1))

Explore your chosen retail time series using the following functions:

autoplot()

autoplot(myseries)
## Plot variable not specified, automatically selected `.vars = Turnover`

gg_season()

gg_season(myseries)
## Plot variable not specified, automatically selected `y = Turnover`

gg_subseries()

gg_subseries(myseries)
## Plot variable not specified, automatically selected `y = Turnover`

gg_lag()

gg_lag(myseries)
## Plot variable not specified, automatically selected `y = Turnover`

ACF() %>% autoplot()

myseries %>%
  ACF(Turnover) %>%
  autoplot()

Can you spot any seasonality, cyclicity and trend? What do you learn about the series?

There is an upward trend as well as seasonality with increases in sales during the holiday season (late Fall until end of December). I do not see any cyclicity as the data highs and lows are predictable (indicating seasonality) and no unpredictable variabilty.

While there is an upward trend, it is interesting to note that the period between 1990 and 2000 shows relatively flat growth in retail sales. After 2000, there is a clear, strong upward trend.