Exercise 2.1

Explore the following four time series: Bricks from aus_production, Lynx from pelt, Close from gafa_stock, Demand from vic_elec.

  1. Use ? (or help()) to find out about the data in each series.
  2. What is the time interval of each series? c Use autoplot() to produce a time plot of each series. d For the last plot, modify the axis labels and title.
# (a) data in each series
?aus_production
?pelt
?gafa_stock 
?vic_elec
# (b) time interval
interval(aus_production)   # 1Q = quarterly
## <interval[1]>
## [1] 1Q
interval(pelt)              # 1Y = annual
## <interval[1]>
## [1] 1Y
interval(gafa_stock)        # ! = irregular (trading days only, no fixed gap)
## <interval[1]>
## [1] !
interval(vic_elec)          # 30m = half-hourly
## <interval[1]>
## [1] 30m
# (c) time plots
aus_production |> autoplot(Bricks, colour = 'hotpink')

pelt |> autoplot(Lynx, colour = "firebrick")

gafa_stock |> autoplot(Close, colour = "limegreen")

vic_elec |> autoplot(Demand, colour = "magenta")

# (d) relabeled plot
vic_elec |> autoplot(Demand, colour = "gold") +
  labs(
    title ="Recorded electricity demand (every 30 minutes):Victoria, Australia",
    x = "Time",
    y = "Demand (MWh)"
  ) +
  theme(
    plot.title = element_text(hjust = 0.5, colour = "gold", face = "bold"),
    axis.title = element_text(colour = "gold", face = "bold"),
    panel.background = element_rect(fill = "navyblue"),
    plot.background = element_rect(fill = "navyblue"),
    panel.grid = element_line(colour = "white"),
    axis.text = element_text(colour = "gold", face = "bold")
  )

Exercise 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)) |>
  ungroup() |>
  select(Symbol, Date, Close)
## # A tsibble: 4 x 3 [!]
## # Key:       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.

Exercise 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) Read the data into R form the csv

tute1 <- readr::read_csv("tute1.csv")
## Rows: 100 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl  (3): Sales, AdBudget, GDP
## date (1): Quarter
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
glimpse(tute1)
## Rows: 100
## Columns: 4
## $ Quarter  <date> 1981-03-01, 1981-06-01, 1981-09-01, 1981-12-01, 1982-03-01, …
## $ Sales    <dbl> 1020.2, 889.2, 795.0, 1003.9, 1057.7, 944.4, 778.5, 932.5, 99…
## $ AdBudget <dbl> 659.2, 589.0, 512.5, 614.1, 647.2, 602.0, 530.7, 608.4, 637.9…
## $ GDP      <dbl> 251.8, 290.9, 290.8, 292.4, 279.1, 254.0, 295.6, 271.7, 259.6…
# (b) convert to tsibble
mytimeseries <- tute1 |>
  mutate(Quarter = yearquarter(Quarter)) |>
  as_tsibble(index = Quarter)

mytimeseries
## # A tsibble: 100 x 4 [1Q]
##    Quarter Sales AdBudget   GDP
##      <qtr> <dbl>    <dbl> <dbl>
##  1 1981 Q1 1020.     659.  252.
##  2 1981 Q2  889.     589   291.
##  3 1981 Q3  795      512.  291.
##  4 1981 Q4 1004.     614.  292.
##  5 1982 Q1 1058.     647.  279.
##  6 1982 Q2  944.     602   254 
##  7 1982 Q3  778.     531.  296.
##  8 1982 Q4  932.     608.  272.
##  9 1983 Q1  996.     638.  260.
## 10 1983 Q2  908.     582.  280.
## # ℹ 90 more rows
# (c) time series plots, faceted
mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, colour = name)) +
  geom_line() +
  facet_grid(name ~ ., scales = "free_y")

# Checking what happens when you don’t include facet_grid().
# Without facet_grid(), all three series share a single y-axis, which compresses GDP's variation (since its values are much smaller than Sales and AdBudget) and makes it harder to see its trend clearly. facet_grid(name ~ ., scales = "free_y") gives each series its own scale, making all three trends individually readable.

mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, colour = name)) +
  geom_line()

Exercise 2.4

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

# (a)Install the USgas packag
library(USgas)
#(b)Create a tsibble from us_total with year as the index and state as the key.
us_total_ts <- us_total |>
  as_tsibble(index = year, key = state)

us_total_ts
## # A tsibble: 1,266 x 3 [1Y]
## # Key:       state [53]
##     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
##  7  2003 Alabama 350345
##  8  2004 Alabama 382367
##  9  2005 Alabama 353156
## 10  2006 Alabama 391093
## # ℹ 1,256 more rows
# (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).
us_total_ts |>
  filter(state %in% c("Maine", "Vermont", "New Hampshire", 
                       "Massachusetts", "Connecticut", "Rhode Island")) |>
  autoplot(y) +
  scale_y_continuous(labels = scales::comma) +
  labs(
    title = "Annual Natural Gas Consumption: New England States",
    x = "Year",
    y = "Consumption"
  )

Exercise 2.5

  1. Download tourism.xlsx from the book website and read it into R using readxl::read_excel().
  2. Create a tsibble which is identical to the tourism tsibble from the tsibble package.
  3. Find what combination of Region and Purpose had the maximum number of overnight trips on average.
  4. Create a new tsibble which combines the Purposes and Regions, and just > has total trips by State.
#(a)

tourism_raw <- readxl::read_excel("tourism.xlsx")
#(b)

tourism_ts <- tourism_raw |>
  mutate(Quarter = yearquarter(Quarter)) |>
  as_tsibble(index = Quarter, key = c(Region, State, Purpose))

tourism_ts
## # A tsibble: 24,320 x 5 [1Q]
## # Key:       Region, State, Purpose [304]
##    Quarter Region   State           Purpose  Trips
##      <qtr> <chr>    <chr>           <chr>    <dbl>
##  1 1998 Q1 Adelaide South Australia Business  135.
##  2 1998 Q2 Adelaide South Australia Business  110.
##  3 1998 Q3 Adelaide South Australia Business  166.
##  4 1998 Q4 Adelaide South Australia Business  127.
##  5 1999 Q1 Adelaide South Australia Business  137.
##  6 1999 Q2 Adelaide South Australia Business  200.
##  7 1999 Q3 Adelaide South Australia Business  169.
##  8 1999 Q4 Adelaide South Australia Business  134.
##  9 2000 Q1 Adelaide South Australia Business  154.
## 10 2000 Q2 Adelaide South Australia Business  169.
## # ℹ 24,310 more rows
#(c)
tourism_ts |>
  as_tibble() |>
  group_by(Region, Purpose) |>
  summarise(Trips = mean(Trips), .groups = "drop") |>
  filter(Trips == max(Trips))
## # A tibble: 1 × 3
##   Region Purpose  Trips
##   <chr>  <chr>    <dbl>
## 1 Sydney Visiting  747.
#(d)
tourism_state <- tourism_ts |>
  as_tibble() |>
  group_by(State, Quarter) |>
  summarise(Trips = sum(Trips), .groups = "drop") |>
  as_tsibble(index = Quarter, key = State)

tourism_state
## # A tsibble: 640 x 3 [1Q]
## # Key:       State [8]
##    State Quarter Trips
##    <chr>   <qtr> <dbl>
##  1 ACT   1998 Q1  551.
##  2 ACT   1998 Q2  416.
##  3 ACT   1998 Q3  436.
##  4 ACT   1998 Q4  450.
##  5 ACT   1999 Q1  379.
##  6 ACT   1999 Q2  558.
##  7 ACT   1999 Q3  449.
##  8 ACT   1999 Q4  595.
##  9 ACT   2000 Q1  600.
## 10 ACT   2000 Q2  557.
## # ℹ 630 more rows

Exercise 2.8

Use the following graphics functions: autoplot(), gg_season(), gg_subseries(), gg_lag(), ACF() and explore features from the following time series: “Total Private” Employed from us_employment, Bricks from aus_production, Hare from pelt, “H02” Cost from PBS, and Barrels from us_gasoline. a) Can you spot any seasonality, cyclicity and trend? b) What do you learn about the series? c) What can you say about the seasonal patterns? d) Can you identify any unusual years?

# # us_employment has many job categories mixed together, so I'm 
# narrowing down to just "Total Private" -- the one the exercise asks about
total_priv <- us_employment |>
  filter(Title == "Total Private")
# is there a long-term trend up or down? Any big dips (recessions)?
total_priv |> autoplot(Employed)

# do all the yearly lines follow a similar shape at the same months?
# That would mean there's a seasonal pattern tied to the calendar.
total_priv |> gg_season(Employed)

# does the average (horizontal line) differ noticeably month to month?
# Confirms whether the seasonal pattern I saw above is real.
total_priv |> gg_subseries(Employed)

#do the points cluster tightly along a diagonal line?
# Tight clustering means the value strongly predicts the next one at that lag.
total_priv |> gg_lag(Employed, geom = "point")

#do the bars spike higher at regular intervals (e.g. every 12 lags)?
# That's numerical confirmation of the seasonality I'm looking for visually above.
total_priv |> ACF(Employed) |> autoplot()

# Bricks remaining plots
aus_production |> gg_season(Bricks)

aus_production |> gg_subseries(Bricks)

aus_production |> gg_lag(Bricks, geom = "point")

aus_production |> ACF(Bricks) |> autoplot()

# Hare (annual data no sub-yearly period, so gg_season() and gg_subseries() 

pelt |> autoplot(Hare)

pelt |> gg_lag(Hare, geom = "point")

pelt |> ACF(Hare) |> autoplot()

# H02 from PBS
# PBS is keyed by Concession, Type, and ATC2 filtering ATC2 alone still leaves
# multiple series,we sum across the other keys to get one combined series
h02 <- PBS |> 
  filter(ATC2 == "H02") |>
  summarise(Cost = sum(Cost))

h02 |> autoplot(Cost)

h02 |> gg_season(Cost)

h02 |> gg_subseries(Cost)

h02 |> gg_lag(Cost, geom = "point")

h02 |> ACF(Cost) |> autoplot()

# Barrels
us_gasoline |> autoplot(Barrels)

us_gasoline |> gg_season(Barrels)

us_gasoline |> gg_subseries(Barrels)

us_gasoline |> gg_lag(Barrels, geom = "point")

us_gasoline |> ACF(Barrels) |> autoplot()

Findings

“Total Private” Employed (us_employment)

  1. Employment kept going up for 80 years, growing about 5 times bigger from 1940 to 2020. There isn’t much seasonality. The dip around 2008 to 2010 was caused by the Great Recession, not by the time of year.
  2. The long-term growth is the main story here. Small ups and downs don’t matter much, only big recessions cause a real drop.
  3. Month to month, employment barely changes. There’s no strong pattern tied to a specific month.
  4. 2008 to 2010 is the one bad stretch, a clear break in an otherwise steady climb.

Bricks (aus_production)

  1. Production went up from 1956 to about 1980, then went back down. On top of that, there’s a repeating yearly pattern: it’s usually lowest in Q1 and highest in Q2 or Q3.
  2. The average amount made in Q3 (about 430) is clearly higher than in Q1 (about 365), so the season really does matter here.
  3. This same low-Q1, high-Q3 pattern shows up almost every single year.
  4. One quarter in the early 1980s drops way lower than it should, a clear one-off outlier.

Hare (pelt)

  1. No long-term trend, the numbers just go up and down in a repeating cycle. No seasonality either since this is yearly data. The cycle repeats roughly every 9 to 10 years.
  2. This is the classic hare and lynx story: hares boom, lynx eat more and boom too, lynx eat too many hares, both crash, then it starts over.
  3. Doesn’t apply, yearly data has no “season” to look at.
  4. 1865 stands out as the biggest hare boom in the whole 90 years, way higher than any other peak.

H02 Cost (PBS)

  1. Cost keeps rising overall, tripling from 1991 to 2008. It also has a very strong yearly pattern: it drops hard every January and February, then climbs all year to a peak in December.
  2. This looks tied to a government program: people probably fill prescriptions before the year ends to use up their benefits, so December spikes and the new year drops.
  3. February is always the lowest month, December and January are always the highest. This happens every year without fail.
  4. The last couple of years look a bit more up-and-down than the earlier ones.

Barrels (us_gasoline)

  1. Usage went up steadily from 1990 to the mid-2000s, then flattened out instead of continuing to grow. There’s also a strong repeating weekly pattern all the way through.
  2. Gas use grew a lot in the 90s and early 2000s, then stopped growing, probably because cars got more fuel-efficient.
  3. The seasonal ups and downs repeat the same way every year, so it’s a real, reliable pattern.
  4. Unlike the employment data, there’s no single bad year here, it just slowly levels off instead of crashing.