Chapter 2 - Time Series Graphics

2.1

  1. Use the help function to explore what the series gafa_stock, PBS, vic_elec and pelt represent.
  1. Use autoplot() to plot some of the series in these data sets.
  2. What is the time interval of each series?
?gafa_stock
## starting httpd help server ... done
?PBS
?vic_elec
?pelt

A

# a
gafa_stock %>% 
  autoplot(Close) +
  labs(title = 'Gafa Stock Closing Prices')

PBS %>% 
  autoplot(Cost) +
  theme(legend.position =  'none') +
  labs(title = 'Monthly Medicare Australia Presciptive Data',
       subtitle = 'Total Number of Scripts')

vic_elec %>% 
  autoplot(Temperature) +
  labs(title = 'Temperature of Melbourne')

pelt %>% 
  autoplot(Hare) +
  labs(title = 'Snowshoe Hare Pelts Traded')

B

The time interval for each series are:

gafa_stock: Day PBS: Month vic_elec: 30 minutes pelt: Year

2.2

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

symbol_names <- as.list(distinct(gafa_stock, Symbol))

gafa_stock %>%
  filter(Symbol == 'AAPL') %>%
  filter(Close == max(Close)) %>%
  select(Symbol)
## # A tsibble: 1 x 2 [!]
## # Key:       Symbol [1]
##   Symbol Date      
##   <chr>  <date>    
## 1 AAPL   2018-10-03
gafa_stock %>%
  filter(Symbol == 'AMZN') %>%
  filter(Close == max(Close)) %>%
  select(Symbol)
## # A tsibble: 1 x 2 [!]
## # Key:       Symbol [1]
##   Symbol Date      
##   <chr>  <date>    
## 1 AMZN   2018-09-04
gafa_stock %>%
  filter(Symbol == 'FB') %>%
  filter(Close == max(Close)) %>%
  select(Symbol)
## # A tsibble: 1 x 2 [!]
## # Key:       Symbol [1]
##   Symbol Date      
##   <chr>  <date>    
## 1 FB     2018-07-25
gafa_stock %>%
  filter(Symbol == 'GOOG') %>%
  filter(Close == max(Close)) %>%
  select(Symbol)
## # A tsibble: 1 x 2 [!]
## # Key:       Symbol [1]
##   Symbol Date      
##   <chr>  <date>    
## 1 GOOG   2018-07-26

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
## 
## i Use `spec()` to retrieve the full column specification for this data.
## i 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 = yearmonth(Quarter)) %>%
  as_tsibble(index = Quarter)

c.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()

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).
#install.packages('USgas')

us_total %>%
  filter(state == c('Maine','Vermont', 'New Hampshire', 'Massachusetts', 'Connecticut', 'Rhode Island')) %>%
 as_tsibble(key = state, index = year) %>%
  autoplot(y) +
  labs(title = 'Annual Natural Gas Consumption by State',
       y = 'Natural Gas Consumption')

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_df <- readxl::read_excel('tourism.xlsx')

#b.
tourism_tsibble <- tourism_df %>% 
  mutate(Quarter = yearquarter(Quarter)) %>%
  as_tsibble(key = c(Region, State, Purpose),
             index = Quarter)

#c. Region = Sydney and Purpose = Visiting has the highest average
#of overnight trips
tourism_df %>%
  group_by(Region, Purpose) %>%
  summarise(avg_trips = mean(Trips)) %>%
  arrange(desc(avg_trips))
## `summarise()` has grouped output by 'Region'. You can override using the `.groups` argument.
## # A tibble: 304 x 3
## # Groups:   Region [76]
##    Region          Purpose  avg_trips
##    <chr>           <chr>        <dbl>
##  1 Sydney          Visiting      747.
##  2 Melbourne       Visiting      619.
##  3 Sydney          Business      602.
##  4 North Coast NSW Holiday       588.
##  5 Sydney          Holiday       550.
##  6 Gold Coast      Holiday       528.
##  7 Melbourne       Holiday       507.
##  8 South Coast     Holiday       495.
##  9 Brisbane        Visiting      493.
## 10 Melbourne       Business      478.
## # ... with 294 more rows
#d.
tourism_tsibble_2 <- tourism_tsibble %>%
  group_by(State) %>%
  summarise(Trips = sum(Trips))

tourism_tsibble_2 %>%
  autoplot(Trips) %>%
  labs(title = 'Total Trips by State')
## [[1]]

## 
## $title
## [1] "Total Trips by State"
## 
## attr(,"class")
## [1] "labels"

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

Explore your chosen retail time series using the following functions:

autoplot(), gg_season(), gg_subseries(), gg_lag(),

ACF() %>% autoplot()

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

The graphing Austrailian Supermarket and grocery data using the Autoplot shows that there are obvious trend that is increasing and a seasonal pattern

The gg_season and gg_subseries graph indicates that there is a seasonal pattern Retail is higher from October to March than the other months.

The gg_lag graph shows a strong correlation in the months prior. However, the 3,6, and 9 lags a slightly less than the other lags. This can support that there is a seasonal pattern in the retail data.

The ACF and Autoplot graph, likewise, supports that there is both a seasonal pattern and a trend with a decreasing scalloped shape.

myseries %>%
  autoplot(Turnover) +
  labs(title = 'Myseries Using Autoplot')

myseries %>%
  gg_season(Turnover, labels = 'both')+
  expand_limits(x = ymd(c("1972-12-20", "1973-12-10"))) +
  labs(title = 'Myseries Using gg_season')

myseries %>%
  gg_subseries(Turnover) +
  labs(title = 'Myseries Using gg_subseries')

myseries %>%
  gg_lag(Turnover, geom = 'point') +
  labs(title = 'Myseries Using gg_lag')

myseries %>% 
  ACF(Turnover) %>%
  autoplot() +
  labs(title = 'Myseries Using ACF & autplot')