Part A

Forecast how much cash is taken out of 4 different ATM machines for May 2010. The variable ‘Cash’ is provided in hundreds of dollars. Explain and demonstrate your process, techniques used, and not used, and your actual forecast. Please provide your written report on your findings, visual, discussion and your R code via RPubs. Also please submit the forecast which you will put in an excel readable file.

library(tsibble)
## 
## Attaching package: 'tsibble'
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, union
library(ggplot2)
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(fpp3)
## -- Attaching packages ---------------------------------------------- fpp3 0.5 --
## v tibble      3.0.3     v feasts      0.3.1
## v tidyr       1.1.1     v fable       0.3.1
## v lubridate   1.7.9     v fabletools  0.3.3
## v tsibbledata 0.4.1
## -- Conflicts ------------------------------------------------- fpp3_conflicts --
## x lubridate::date()      masks base::date()
## x dplyr::filter()        masks stats::filter()
## x fabletools::forecast() masks forecast::forecast()
## x tsibble::intersect()   masks base::intersect()
## x lubridate::interval()  masks tsibble::interval()
## x dplyr::lag()           masks stats::lag()
## x tsibble::setdiff()     masks base::setdiff()
## x tsibble::union()       masks base::union()
library(readxl)
ts <- read_excel("ATM624DATA.xlsx", col_types = c('date', 'text', 'numeric')) %>%
  #convert to date format
  mutate(DATE = as_date(DATE))  %>%
  #convert to tsibble
  as_tsibble(index = DATE, key = ATM) %>%
  #Target only dates BEFORE may 2010
  filter(DATE < "2010-05-01")

head(ts)
## # A tsibble: 6 x 3 [1D]
## # Key:       ATM [1]
##   DATE       ATM    Cash
##   <date>     <chr> <dbl>
## 1 2009-05-01 ATM1     96
## 2 2009-05-02 ATM1     82
## 3 2009-05-03 ATM1     85
## 4 2009-05-04 ATM1     90
## 5 2009-05-05 ATM1     99
## 6 2009-05-06 ATM1     88
summary(ts)
##       DATE                ATM                 Cash        
##  Min.   :2009-05-01   Length:1460        Min.   :    0.0  
##  1st Qu.:2009-07-31   Class :character   1st Qu.:    0.5  
##  Median :2009-10-30   Mode  :character   Median :   73.0  
##  Mean   :2009-10-30                      Mean   :  155.6  
##  3rd Qu.:2010-01-29                      3rd Qu.:  114.0  
##  Max.   :2010-04-30                      Max.   :10919.8  
##                                          NA's   :5

This data frame contains 3 columns; a date column in the format of yer-month-day, an ATM column that identifies which ATM the transaction was done at, and a CASH column that represents the amount of money taken out at that point in time in hundreds of USD. there are 13 rows that are missing data that will likely need to be removed or otherwise fixed before processing can begin.

ts <- ts %>%
  #Use ARIMA to imputate the missing values
  model(ARIMA(Cash)) %>%
  interpolate(ts)

#Confirm there are no more missing values
ts %>% 
  as.data.frame() %>%
  group_by(ATM) %>%
  summarise("Missing Values" = sum(is.na(Cash)))
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 4 x 2
##   ATM   `Missing Values`
##   <chr>            <int>
## 1 ATM1                 0
## 2 ATM2                 0
## 3 ATM3                 0
## 4 ATM4                 0
#check the grpahs
ggplot(data = ts, aes(x = DATE, y = Cash, group = ATM, color = ATM)) +
  geom_line() +
  labs(title = "Time Series Plot",
       x = "Date",
       y = "Cash") +
  facet_wrap(~ ATM, scales = "free_y")

As we can see, ATM’s 1 and 2 have mostly consistent withdrawals through the time period being looked at, but 3 and 4 have some serious outlier withdrawals going on at the end of the data chronologically. In regards to seasonality; just eyeballing it, ATM1 and 2 have clear seasonality, while ATM4 might have seasonality though it is a little hard to tell with that outlier skewing the graph so badly. ATM 3 looks like it went basically unused until the middle of 2010 after which it’s usage shot up.

After looking at these graphs, i think the best course of action is to just remove ATM3 from the dataset, its mostly 0 and is messing with the data too much. I also think that outliers in ATM4 should be changed to the median value to make the graph more readable.

# Remove rows with ATM value "ATM3"
ts <- ts %>%
  filter(ATM != "ATM3")

#Calculate the median of ATM4
median_value <- median(ts$Cash[ts$ATM == "ATM4"], na.rm = TRUE)

#Define the threshold for identifying outliers
outlier_threshold <- 1.5 * IQR(ts$Cash[ts$ATM == "ATM4"])

# Replace outliers in ATM4 with the median of ATM4
ts <- ts %>%
  mutate(Cash = ifelse(ATM == "ATM4" & abs(Cash - median_value) > outlier_threshold, median_value, Cash))

#check the graphs again
ggplot(data = ts, aes(x = DATE, y = Cash, group = ATM, color = ATM)) +
  geom_line() +
  labs(title = "Time Series Plot",
       x = "Date",
       y = "Cash") +
  facet_wrap(~ ATM, scales = "free_y")

with the data cleaned up, we have a much clearer picture of seasonality in these graphs and can now begin looking at the metadata of the transactions to check for interesting patterns in the data.

#list of ATM values we are examining
atm_vals = c("ATM1", "ATM2", "ATM4")

#loop through all ATMS
for(atm_val in atm_vals) {
  #target only specific ATM
  atm_filtered = ts %>% filter(ATM == atm_val)
  
  #get STL decomposition
  print(atm_filtered %>%
  model(STL(Cash ~ season(window = "periodic"), robust = TRUE)) %>%
  components() %>%
  autoplot() +
  labs(title = sprintf("STL Decomposition for %s", atm_val)))
  
  #box cox transformation function
  lambda <- atm_filtered %>%
    features(Cash, features = guerrero) %>%
    pull(lambda_guerrero)

  atm_fit <- atm_filtered %>%
      model(
        #additive ETS
        additive_ts = ETS(box_cox(Cash,lambda) ~ error("A") + trend("N") + season("A")),
        
        #ARIMA model
        ARIMA = ARIMA(box_cox(Cash,lambda)),
      
        #multiplicative ETS
        multiplicative_ts = ETS(box_cox(Cash,lambda) ~ error("M") + trend("N") + season("M")),
      
        #SNAIVE
        snaive_ts = SNAIVE(box_cox(Cash,lambda))
      )

      #report of the ARIMA model
      report(atm_fit 
             %>% select(.model = "ARIMA")
             )

      #forecast
      atm_forecast <- atm_fit %>%
        forecast(h = 50) %>%
        filter(.model == 'ARIMA')

      #forcasted plot saved as variable for excel formatting
      f_cast = atm_forecast %>%
        autoplot(ts) +
        ggtitle(sprintf("%s ARIMA Forecasted", atm_val))
      
      #print the forecast (in loops, graphs have to be explcitly rendered in R)
      print(f_cast)
      
      #save as png for excel friendly format
      ggsave(sprintf("%s.png", atm_val), plot = f_cast, width = 6, height =4, dpi=300)
      

      #residuals
      print(atm_fit %>%
        select(ARIMA) %>%
        gg_tsresiduals() +
        ggtitle(sprintf("Residuals for %s", atm_val)))
}

## Series: Cash 
## Model: ARIMA(0,0,2)(0,1,1)[7] 
## Transformation: box_cox(Cash, lambda) 
## 
## Coefficients:
##          ma1      ma2     sma1
##       0.1105  -0.1088  -0.6419
## s.e.  0.0524   0.0521   0.0431
## 
## sigma^2 estimated as 1.771:  log likelihood=-610.69
## AIC=1229.38   AICc=1229.49   BIC=1244.9

## Series: Cash 
## Model: ARIMA(2,0,2)(0,1,1)[7] 
## Transformation: box_cox(Cash, lambda) 
## 
## Coefficients:
##           ar1      ar2     ma1     ma2     sma1
##       -0.4180  -0.9012  0.4579  0.7889  -0.7129
## s.e.   0.0592   0.0475  0.0888  0.0619   0.0419
## 
## sigma^2 estimated as 44.97:  log likelihood=-1188.76
## AIC=2389.51   AICc=2389.75   BIC=2412.8

## Series: Cash 
## Model: ARIMA(0,0,0)(2,0,0)[7] w/ mean 
## Transformation: box_cox(Cash, lambda) 
## 
## Coefficients:
##         sar1    sar2  constant
##       0.1955  0.2227   26.5934
## s.e.  0.0513  0.0518    1.1890
## 
## sigma^2 estimated as 542:  log likelihood=-1665.88
## AIC=3339.77   AICc=3339.88   BIC=3355.37

looking at the summary data for ATM1, it seems like the snaive_ts model performed the worst, with the rest of the models being fairly close in performance. I chose to use the ARIMA model for the forecasting. The residuals look like random noise and the lag chart has few outliers. For ATM2 and ATM4 the summary of the different models once again showed that the ARIMA model would perform the best. Since all 3 were following the same path, I decided to put this into a loop to save some time on coding. All 3 ATMS that were included in the forecast showed seasonality and little trend. the curve on the residuals graph is mostly normal for ATMs 2 and 4, but ATM1 skews a little to the right. There are some outliers but given the bigger piture of the .resid and residuals line graph, i believe this to be overlookable.

Part B

Part B consists of a simple dataset of residential power usage for january 1998 until december 2013. Your assignment is to model these data and a monthly forecast for 2014. The data is given in a single file. The variable ‘KWH’ is power consumption in Kilowatt hours, the rest is straight forward. Add this to your existing files above

filePath <- "ResidentialCustomerForecastLoad-624.xlsx"

tb <- read_excel(filePath) %>%
  #rename the date to something more normal
  rename(DATE = 'YYYY-MMM') %>%
  #set time column as date
  mutate(DATE = yearmonth(DATE)) %>%
  #convert to tsibble
  as_tsibble(index = DATE)

head(tb)
## # A tsibble: 6 x 3 [1M]
##   CaseSequence     DATE     KWH
##          <dbl>    <mth>   <dbl>
## 1          733 1998 Jan 6862583
## 2          734 1998 Feb 5838198
## 3          735 1998 Mar 5420658
## 4          736 1998 Apr 5010364
## 5          737 1998 May 4665377
## 6          738 1998 Jun 6467147
summary(ts)
##      ATM                 DATE                 Cash        
##  Length:1095        Min.   :2009-05-01   Min.   :   0.00  
##  Class :character   1st Qu.:2009-07-31   1st Qu.:  56.00  
##  Mode  :character   Median :2009-10-30   Median :  92.48  
##                     Mean   :2009-10-30   Mean   : 191.37  
##                     3rd Qu.:2010-01-29   3rd Qu.: 146.50  
##                     Max.   :2010-04-30   Max.   :1245.59

Data looks pretty ordinary at first glance. There are a few missing values that need to be imputated, going to use ARIMA to set their values. When inspecting the data, i noticed a single bad outlier, so i will also take this opportunity to set that value to NA so it gets impuated to something closer to the mean and makes the data set more normal and easier to work with going forward.

#fix the issue with the outlier data
# Define the threshold for identifying outliers, ignore NA values
outlier_threshold <- 2 * IQR(tb$KWH, na.rm =TRUE)

# Replace outliers with NA
tb$KWH[abs(tb$KWH - median(tb$KWH)) > outlier_threshold] <- NA

tb <- tb %>%
  # Fit ARIMA model to the data containing missing values
  model(ARIMA(KWH)) %>%
  # Estimate Cash for the missing values.
  interpolate(tb)

the data should be clean now, both of NA values, and the outliers that we were seeing earlier

# Time Series Plot
ggplot(tb, aes(x = DATE, y = KWH)) +
  geom_line() +
  labs(title = "Time Series Plot", x = "Date", y = "kWh")

# Scatter Plot
ggplot(tb, aes(x = DATE, y = KWH)) +
  geom_point() +
  labs(title = "Scatter Plot", x = "Date", y = "kWh")

# Perform STL decomposition
stl_decomp <- tb %>%
  model(STL(KWH ~ season(window = "periodic")))

# Extract the components
stl_components <- components(stl_decomp)

# Create a plot of the components
ggplot(stl_components, aes(x = DATE)) +
  geom_line(aes(y = season_adjust, color = "Seasonal")) +
  geom_line(aes(y = trend, color = "Trend")) +
  geom_line(aes(y = remainder, color = "Remainder")) +
  scale_color_manual(values = c("Seasonal" = "blue", "Trend" = "red", "Remainder" = "green")) +
  labs(title = "STL Decomposition", x = "Date", y = "Value") +
  theme_minimal()

#get STL decomposition
tb %>%
  model(STL(KWH ~ season(window = "periodic"), robust = TRUE)) %>%
  components() %>%
  autoplot() +
  labs(title = "STL Decomposition for electricty")

The data looks pretty consistent, with a single outlier around january of 2010. there is also clear seasonality going on here and possibly a slight upward trend? It’s hard to tell at this point so let’s just continue onward.

tb %>%
  gg_season(KWH, labels = "both") +
  labs(title = "Seasonal plot: Residential Power Usage")

tb %>%
  gg_subseries(KWH) +
  labs(title = "Residential Power Usage")

tb %>%
  gg_lag(KWH, lag_max = 20) +
  labs(title = "Lag Plot: Residential Power Usage")

# PACF plot
pacf_result <- Pacf(tb)

plot(pacf_result, main = "PACF Plot: Residential Power Usage")

The seasonal plot shows that power usage is highest in the winter and summer, with valleys in the fall and spring (huge shock there). There are correlations in the lag in the ACF plots.

#box-cox (lol) transformation function
lambda <- tb %>%
  features(KWH, features = guerrero) %>%
  pull(lambda_guerrero)


ele_fit <- tb %>%
  model(
    # transformed multiplicative ETS model
    multiplicative_bc = ETS(box_cox(KWH,lambda) ~ error("M") + trend("A") + season("M")),
    
    # transformed additive damped model
    damped_bc = ETS(box_cox(KWH,lambda) ~ error("A") + trend("Ad") + season("A")),
    
    # transformed SNAIVE model
    snaive_bc = SNAIVE(box_cox(KWH,lambda)),
    
    # arima model
    ARIMA = ARIMA(box_cox(KWH,lambda))
  )


 # forecasting
fc_res <- ele_fit %>%
  forecast(h = 12) %>%
  filter(.model=='ARIMA')

# forcasted plot
fc = fc_res %>%
  autoplot(tb) +
  ggtitle("KWH Forecast")
print(fc)

#Save value for excel format
ggsave("KHW.png", plot=fc, width=8, height=6, dpi=300)

# residuals
ele_fit %>%
  select(ARIMA) %>%
  gg_tsresiduals(lag = 24) +
  ggtitle("Residuals for kwh")

I tested out 4 types of models for forecasting but in the end, decided to go with ARIMA model because it had the best AIC, AICc, and BIC values as seen in the summary function. the residuals are mostly white noise except for one weird outlier near the beginning of 2010. the .resid graph is somewhat normal but skews to the right. the lag chart shows few outliers and no real order.