library(readr)
library(tsibble)
library(dplyr)
library(feasts)
library(fable)
library(ggplot2)
# Reading Data
honda <- read_csv("data/HMC.csv")
toyota <- read_csv("data/TM.csv")

# Merging Data
all <- dplyr::bind_cols(honda[,c(1,5)], toyota[,5])
names(all) <- c("Date", "Honda", "Toyota")

# Formatting Data
all$Date = yearmonth(as.Date(all$Date))
all = slice(all, 1:(n() - 1))
all = all %>% as_tsibble(index = Date)



# Plotting
ggplot(data = all, mapping=aes(x = Date)) + 
  geom_line(aes(y = log(Honda)), color = 'red') + 
  geom_line(aes(y = log(Toyota)), color = 'blue') + 
  ggtitle("Natural Log of Closing Price for  Honda (red)  and  Toyota (blue)") + 
  ylab("Natural Log of Closing Price")

# Modeling
fit <- all %>%
  model(
    aicc = VAR(vars(Honda, Toyota)), 
    bic = VAR(vars(Honda, Toyota), ic = "bic")
  )
fit
# A mable: 1 x 2
      aicc      bic
   <model>  <model>
1 <VAR(2)> <VAR(1)>
glance(fit)
# A tibble: 2 x 6
  .model sigma2        log_lik   AIC  AICc   BIC
  <chr>  <list>          <dbl> <dbl> <dbl> <dbl>
1 aicc   <dbl [2 x 2]>   -291.  607.  614.  631.
2 bic    <dbl [2 x 2]>   -298.  612.  615.  629.
fit %>% 
  augment() %>%
  ACF(.innov) %>%
  autoplot()

# There are no significant autocorrelations for either manufacturers stock price. All information in
# the data is captured by the model. 

fit %>% 
  select(aicc) %>%
  forecast() %>%
  autoplot(all)