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

Q1a. Use ? (or help()) to find out about the data in each series.

#?("aus_production")

Q1b. What is the time interval of each series?

The time interval for aus_production is quarterly estimates of selected indicators in Australia. The time interval for pelt is yearly from 1845 to 1935. The time interval for gafa_stock are daily trading days from 2014 to 2018. The time interval for vic_elec are half-hourly.

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

autoplot(aus_production,Bricks) + ggtitle("Quarterly Productions of Bricks in Australia")
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

autoplot(pelt,Lynx) + ggtitle("Records of Canadian Lynx pelts traded")

autoplot(gafa_stock,Close) + ggtitle("Closing Prices for GAFA stocks")

autoplot(vic_elec,Demand) + ggtitle("Half-hourly electricity Demand")

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

autoplot(vic_elec,color="blue") + labs(title = "modified plot")+ ylab("Demand (MW)") 
## Plot variable not specified, automatically selected `.vars = Demand`

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

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.

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

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

tute1 <- readxl::read_excel("C:/Users/xmei/Desktop/tourism.xlsx")

View(tute1)

Q3b. Convert the data to time series

mytimeseries <- tute1 |>
  mutate(Quarter = yearquarter(Quarter)) |>
  group_by(Quarter) |>
  summarise(across(where(is.numeric), mean)) |>  # or other aggregation
  as_tsibble(index = Quarter)

Q3c. Construct time series plots of each of the three series. Check what happens when you don’t include facet_grid().

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.

mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, colour = name)) +
  geom_line() +
  facet_grid(name ~ ., scales = "free_y")

#second part of the question.
mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, colour = name)) +
  geom_line()

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

Q4a. Install the USgas package.

library(USgas)

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

us_total <- us_total |>
  as_tibble(key = state,
            index = year)

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

# Plotting 
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")

Q5a. Download tourism.xlsx from the book website and read it into R using readxl::read_excel().

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

Q5b.Create a tsibble which is identical to the tourism tsibble from the tsibble package.

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

Q5C. Find what combination of Region and Purpose had the maximum number of overnight trips on average.

Sydney has the max number of overnight trip on average.

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

Q5d.Create a new tsibble which combines the Purposes and Regions, and just has total trips by State.

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

Q8. 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?

Employed from us_employment: “Total Private”, generally upward trend. Seasonality with higher trend in summer season and low in winter season. Time plot and Lags plot shows a business cycle in about 7 years.

us_employment |>
  filter(Title == "Total Private") |>
  autoplot(Employed) + ggtitle("Total Private Employed")

us_employment |>
  filter(Title == "Total Private") |>
  gg_season(Employed)
## Warning: `gg_season()` was deprecated in feasts 0.4.2.
## ℹ Please use `ggtime::gg_season()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

us_employment |>
  filter(Title == "Total Private") |>
  gg_subseries(Employed)
## Warning: `gg_subseries()` was deprecated in feasts 0.4.2.
## ℹ Please use `ggtime::gg_subseries()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

us_employment |>
  filter(Title == "Total Private") |>
  gg_lag(Employed,geom = "point")
## Warning: `gg_lag()` was deprecated in feasts 0.4.2.
## ℹ Please use `ggtime::gg_lag()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

us_employment |>
  filter(Title == "Total Private") |>
  ACF(Employed) |>
  autoplot()

Bricks from aus_production. Bricks, there was an upward trend until around 1978 and generally a down trend. Seasonality Q3 generally has higher production. 1980 production has a significant decline.

aus_production |> autoplot(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

aus_production |> gg_season(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

aus_production |> gg_subseries(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

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

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

Hare from pelt, doesn’t seems there is a clear trend, or seasonality. Seems about 10 years cycle.

pelt |> autoplot(Hare)

pelt |> gg_subseries(Hare)

pelt |> gg_lag(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

“H02” Cost from PBS. ho2_cost, generally trending upward. Montly seasonality with peaks in Jan and Dec. 

H02 <- PBS |> filter(ATC2 == "H02") 
H02 |> autoplot(Cost)

H02 |> gg_season(Cost)

H02 |> gg_subseries(Cost)

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

Barrels from us_gasoline. Barrels. generally going upward, weekly trend can ben seen in gg_season plot, each lines of weekly move in consistent pattern.

us_gasoline |> autoplot(Barrels)

us_gasoline |> gg_season(Barrels)

us_gasoline |> gg_subseries(Barrels)

us_gasoline |> gg_lag(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