Question 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?

  3. Use autoplot() to produce a time plot of each series.

  4. For the last plot, modify the axis labels and title.

Answer:

#Loading required R package and datasets:
library(fpp3)
## Warning: package 'fpp3' was built under R version 4.3.2
## ── Attaching packages ────────────────────────────────────────────── fpp3 0.5 ──
## ✔ tibble      3.2.1     ✔ tsibble     1.1.4
## ✔ dplyr       1.1.3     ✔ tsibbledata 0.4.1
## ✔ tidyr       1.3.0     ✔ feasts      0.3.1
## ✔ lubridate   1.9.3     ✔ fable       0.3.3
## ✔ ggplot2     3.4.4     ✔ fabletools  0.3.4
## Warning: package 'tsibble' was built under R version 4.3.2
## Warning: package 'tsibbledata' was built under R version 4.3.2
## Warning: package 'feasts' was built under R version 4.3.2
## Warning: package 'fabletools' was built under R version 4.3.2
## Warning: package 'fable' was built under R version 4.3.2
## ── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
## ✖ lubridate::date()    masks base::date()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ tsibble::intersect() masks base::intersect()
## ✖ tsibble::interval()  masks lubridate::interval()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ tsibble::setdiff()   masks base::setdiff()
## ✖ tsibble::union()     masks base::union()
library(ggplot2)
data("aus_production")
data("pelt")
data("gafa_stock")
data("vic_elec")
#help("aus_production")
#help("pelt")
#help("gafa_stock")
#help("vic_elec")

Time Travel of each series:

aus_production: Quarterly estimates of selected indicators of manufacturing production in Australia.

pelt: Hudson Bay Company trading records for Snowshoe Hare and Canadian Lynx furs from 1845 to 1935. This data contains trade records for all areas of the company annually (every 12 months).

gafa_stock: GAFA stock prices records data on daily basis.

vic_elec: vic_elec is a half-hourly electricity demand for Victoria, Australia.

autoplot(aus_production,Bricks)+ggtitle("Quarterly Production of Bricks in Australia")
## Warning: Removed 20 rows containing missing values (`geom_line()`).

autoplot(pelt, Lynx) +
  ggtitle("Canadian Lync Pelts traded 1845-1935")

autoplot(gafa_stock, Close) +
  ggtitle("Closing GAFA Stock Prices from 2014-2018")

autoplot(vic_elec, Demand) +
  ggtitle("Electricity Demand for Victoria, Australia")

# Time plot for Electricity Demand in Victoria
autoplot(vic_elec,color="green") + labs(title = "Electricity Demand in Victoria")+ ylab("Demand (MW)") 
## Plot variable not specified, automatically selected `.vars = Demand`

Question 2.2:

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

Answer:

library(dplyr)
data(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.

Question 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.

  1. You can read the data into R with the following script:
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.
View(tute1)
  1. Convert the data to time series
mytimeseries <- tute1 |>
  mutate(Quarter = yearquarter(Quarter)) |>
  as_tsibble(index = Quarter)
  1. Construct time series plots of each of the three series
mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, colour = name)) +
  geom_line() +
  facet_grid(name ~ ., scales = "free_y")

Check what happens when you don’t include facet_grid()

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

The first Chart with facet_grid(): This chart has three separate Y-axes, one for each variable, which allows each to be measured on a scale appropriate to its magnitude. This is evident because the scales for AdBudget, GDP, and Sales are different, allowing for a clearer view of the trends and patterns for each variable without one overshadowing the others due to scale differences.

The second chart without facet_grid(): This chart combines all three variables onto a single Y-axis, which ranges from about 400 to 1000. This makes it more difficult to discern the individual trends of each variable because their values are now directly comparable on the same scale.

Question 2.4:

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

  1. Install the USgas package.

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

  3. 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).

Answer:

library(USgas)
## Warning: package 'USgas' was built under R version 4.3.2
# creating tsibble from us_total
us_total <- us_total %>%
  as_tibble(key = state,
            index = year)

# Plotting annual natural gas consumption
us_total %>%
  filter(state %in% c('Maine', 'Vermont', 'New Hampshire', 'Massachusetts', 'Connecticut', 'Rhode Island')) %>%
  ggplot(aes(x = year, y = y, colour = state)) +
  geom_line() +
  facet_grid(state ~., scales = "free_y") +
  labs(title = "Annual Natural Gas Consumption in New England",
       y = "Consumption")

The chart is a multi-line graph titled “Annual Natural Gas Consumption in New England. Each state is represented by a line of a different color, and the lines are plotted on the same graph but with different scales for each state.

Connecticut which is indicated by Red line has the highest consumption levels among the six, with a generally upward trend over time, reaching close to 280,000 units by the end of the period.

Maine with Yellow line shows relatively low and flat natural gas consumption, with values mostly around 25,000 units, indicating minimal change over time.

Massachusetts indicated by Green line exhibits a slightly undulating pattern with a general upward trend, starting from around 390,000 units and ending near 450,000 units.

New Hampshire with Cyan line starts at around 40,000 units, with a gradual increase over time, reaching about 70,000 units.

Rhode Island defined by Blue line whose consumption levels are relatively stable, with a slight upward trend from around 80,000 units to 100,000 units.

Vermont indicated by Pink line has the lowest consumption levels, starting near the bottom of the chart and showing a slight increase over time, ending around 12,000 units.

Question 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.

Answer:

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

# creating a tsibble
tourism_ts <- tourism %>%
  mutate(Quarter = yearquarter(Quarter)) %>%
  as_tsibble(key = c(Region, State, Purpose),
             index = Quarter)

#finding the maximum number of overnight trips
tourism_ts %>%
  group_by(Region, Purpose) %>%
  mutate(Avg_Trips = mean(Trips)) %>%
  ungroup() %>%
  filter(Avg_Trips == max(Avg_Trips)) %>%
  distinct(Region, Purpose)
## # A tibble: 1 × 2
##   Region Purpose 
##   <chr>  <chr>   
## 1 Sydney Visiting
# creating a new tsibble
tourism %>%
  group_by(Quarter, State) %>%
  mutate(Quarter = yearquarter(Quarter),
         Total_Trips = sum(Trips)) %>%
  select(Quarter, State, Total_Trips) %>%
  distinct() %>%
  as_tsibble(index = Quarter,
             key = State)
## # A tsibble: 640 x 3 [1Q]
## # Key:       State [8]
## # Groups:    State @ Quarter [640]
##    Quarter State Total_Trips
##      <qtr> <chr>       <dbl>
##  1 1998 Q1 ACT          551.
##  2 1998 Q2 ACT          416.
##  3 1998 Q3 ACT          436.
##  4 1998 Q4 ACT          450.
##  5 1999 Q1 ACT          379.
##  6 1999 Q2 ACT          558.
##  7 1999 Q3 ACT          449.
##  8 1999 Q4 ACT          595.
##  9 2000 Q1 ACT          600.
## 10 2000 Q2 ACT          557.
## # ℹ 630 more rows

Question 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.

Can you spot any seasonality, cyclicity and trend?

What do you learn about the series?

What can you say about the seasonal patterns?

Can you identify any unusual years?

Answer:

# filtering Total Private from us_employment
Priv <- us_employment %>% 
        filter(Title == "Total Private")

# performing autoplot
Priv %>% autoplot(Employed)

# performing gg_season
Priv %>% gg_season(Employed)

# performing gg_subseries
Priv %>% gg_subseries(Employed)

# performing gg_lag
Priv %>% gg_lag(Employed)

# performing ACF
Priv %>% ACF(Employed)
## # A tsibble: 29 x 3 [1M]
## # Key:       Series_ID [1]
##    Series_ID          lag   acf
##    <chr>         <cf_lag> <dbl>
##  1 CEU0500000001       1M 0.997
##  2 CEU0500000001       2M 0.993
##  3 CEU0500000001       3M 0.990
##  4 CEU0500000001       4M 0.986
##  5 CEU0500000001       5M 0.983
##  6 CEU0500000001       6M 0.980
##  7 CEU0500000001       7M 0.977
##  8 CEU0500000001       8M 0.974
##  9 CEU0500000001       9M 0.971
## 10 CEU0500000001      10M 0.968
## # ℹ 19 more rows

According to the data chart, there is an arising positive trend in total private employment throughout the course of the year. We can also observe a seasonal pattern in which employment rises during the first half of the year before declining and then increasing again. All of the lag subplots in the lag plot exhibit strong positive relationships. The stark decline in employment for all private jobs in the late 2000s is one item to note.

# performing autoplot for Bricks
aus_production %>% autoplot(Bricks)
## Warning: Removed 20 rows containing missing values (`geom_line()`).

# performing gg_season for Bricks
aus_production %>% gg_season(Bricks)
## Warning: Removed 20 rows containing missing values (`geom_line()`).

# performing gg_subseries for Bricks
aus_production %>% gg_subseries(Bricks)
## Warning: Removed 5 rows containing missing values (`geom_line()`).

# performing gg_lag for Bricks
aus_production %>% gg_lag(Bricks)
## Warning: Removed 20 rows containing missing values (gg_lag).

# performing ACF
aus_production %>% ACF(Bricks)
## # A tsibble: 22 x 2 [1Q]
##         lag   acf
##    <cf_lag> <dbl>
##  1       1Q 0.900
##  2       2Q 0.815
##  3       3Q 0.813
##  4       4Q 0.828
##  5       5Q 0.720
##  6       6Q 0.642
##  7       7Q 0.655
##  8       8Q 0.692
##  9       9Q 0.609
## 10      10Q 0.556
## # ℹ 12 more rows

Although there is no discernible trend in the production of bricks, there is some annual seasonality and some cyclical behavior. Of particular interest is the evident decline in brick output in the first quarter of 1980. According to the seasonal plot, brick production slightly increases in Q1 and Q3, then declines in Q4.

# performing autoplot for Hare
pelt %>% autoplot(Hare)

# performing gg_subseries for Hare
pelt %>% gg_subseries(Hare)

# performing gg_lag for Hare
pelt %>% gg_lag(Hare)

# performing ACF for Hare
pelt %>% ACF(Hare)
## # A tsibble: 19 x 2 [1Y]
##         lag     acf
##    <cf_lag>   <dbl>
##  1       1Y  0.658 
##  2       2Y  0.214 
##  3       3Y -0.155 
##  4       4Y -0.401 
##  5       5Y -0.493 
##  6       6Y -0.401 
##  7       7Y -0.168 
##  8       8Y  0.113 
##  9       9Y  0.307 
## 10      10Y  0.340 
## 11      11Y  0.296 
## 12      12Y  0.206 
## 13      13Y  0.0372
## 14      14Y -0.153 
## 15      15Y -0.285 
## 16      16Y -0.295 
## 17      17Y -0.202 
## 18      18Y -0.0676
## 19      19Y  0.0956

The trading record for hare pelts does not exhibit a distinct trend; however, there is a notable seasonal pattern with some cyclical activity, as well as dramatic rises and falls in the quantity of hare pelts exchanged, which diminishes as the year progresses. A moderately favorable association can be seen in the lag plot, particularly in lags 1 and 2. There is a notable decline in the trading of hare pelts in 1860.

# performing autoplot for H02
H02 <- PBS %>% filter(ATC2 == "H02") 
H02 %>% autoplot(Cost)

# performing gg_season for H02
H02 %>% gg_season(Cost)

# performing gg_subseries for H02
H02 %>% gg_subseries(Cost)

# performing ACF for H02
H02 %>% ACF(Cost)
## # A tsibble: 92 x 6 [1M]
## # Key:       Concession, Type, ATC1, ATC2 [4]
##    Concession   Type        ATC1  ATC2       lag   acf
##    <chr>        <chr>       <chr> <chr> <cf_lag> <dbl>
##  1 Concessional Co-payments H     H02         1M 0.834
##  2 Concessional Co-payments H     H02         2M 0.679
##  3 Concessional Co-payments H     H02         3M 0.514
##  4 Concessional Co-payments H     H02         4M 0.352
##  5 Concessional Co-payments H     H02         5M 0.264
##  6 Concessional Co-payments H     H02         6M 0.219
##  7 Concessional Co-payments H     H02         7M 0.253
##  8 Concessional Co-payments H     H02         8M 0.337
##  9 Concessional Co-payments H     H02         9M 0.464
## 10 Concessional Co-payments H     H02        10M 0.574
## # ℹ 82 more rows

The data refers to fluctuations that occur at specific regular intervals less than a year, such as quarterly or monthly. In the given plots, there might be signs of seasonality if we see patterns that repeat yearly at the same time. It seems that there are multiple categories of costs being tracked, which could be related to different departments, projects, or types of expenses. There seems to be some seasonality, with certain months showing higher costs consistently across different years.

# performing autoplot for Barrels
us_gasoline %>% autoplot(Barrels)

# performing gg_season for Barrels
us_gasoline %>% gg_season(Barrels)

# performing gg_subseries for Barrels
us_gasoline %>% gg_subseries(Barrels)

# performing gg_lag for Barrels
us_gasoline %>% gg_lag(Barrels)

# performing gg_lag for Barrels
us_gasoline %>% ACF(Barrels)
## # A tsibble: 31 x 2 [1W]
##         lag   acf
##    <cf_lag> <dbl>
##  1       1W 0.893
##  2       2W 0.882
##  3       3W 0.873
##  4       4W 0.866
##  5       5W 0.847
##  6       6W 0.844
##  7       7W 0.832
##  8       8W 0.831
##  9       9W 0.822
## 10      10W 0.808
## # ℹ 21 more rows

This series has a positive trend and exhibits seasonality, with peaks and valleys occurring at specific times throughout the month. Because the series has no defined frequency, we can also see cyclic behavior.The lag plot is overplotted and exhibits positive correlation. Additionally, the plot’s seasonality is unchanged.