## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
set.seed(42)
library(bridgr)

## ----data---------------------------------------------------------------------
gdp_growth <- suppressMessages(tsbox::ts_na_omit(tsbox::ts_pc(gdp)))

head(gdp_growth)
head(baro)

## ----stationarity, warning = TRUE---------------------------------------------
gdp_level_recent <- dplyr::slice_tail(gdp, n = 40)
baro_recent <- dplyr::slice_tail(baro, n = 120)

invisible(tryCatch(
  mf_model(
    target = gdp_level_recent,
    indic = baro_recent,
    indic_predict = "last",
    indic_aggregators = "mean",
    h = 1,
    stationarity = "warn"
  ),
  warning = function(w) message("Warning captured: ", conditionMessage(w))
))

stationary_model <- mf_model(
  target = gdp_growth,
  indic = baro,
  indic_predict = "last",
  indic_aggregators = "mean",
  h = 1,
  stationarity = "warn"
)

## ----basic-model--------------------------------------------------------------
bridge_model <- mf_model(
  target = gdp_growth,
  indic = baro,
  indic_predict = "auto.arima",
  indic_aggregators = "mean",
  indic_lags = 1,
  target_lags = 1,
  h = 2
)

forecast(bridge_model)

## ----aligned-data-------------------------------------------------------------
tail(model.frame(bridge_model))
model.frame(bridge_model, which = "forecast")

## ----model-summary------------------------------------------------------------
summary(bridge_model)

## ----forecast-plot------------------------------------------------------------
plot(bridge_model, type = "forecast")

## ----multi-indicator----------------------------------------------------------
baro_yoy <- baro |>
  dplyr::arrange(time) |>
  dplyr::mutate(values = values - dplyr::lag(values, 12)) |>
  dplyr::filter(!is.na(values))

indic_multi <- dplyr::bind_rows(
  dplyr::mutate(baro, id = "baro_level"),
  dplyr::mutate(baro_yoy, id = "baro_yoy")
) |>
  dplyr::select(id, time, values)

multi_model <- mf_model(
  target = gdp_growth,
  indic = indic_multi,
  indic_predict = c("last", "last"),
  indic_aggregators = c("mean", "mean"),
  target_lags = 1,
  h = 1
)

variable.names(multi_model)
forecast(multi_model)

## ----direct-model-------------------------------------------------------------
direct_model <- mf_model(
  target = gdp_growth,
  indic = baro,
  indic_predict = "direct",
  h = 1
)

forecast(direct_model)

## ----uncertainty-example------------------------------------------------------
uncertainty_model <- mf_model(
  target = gdp_growth,
  indic = baro,
  indic_predict = "auto.arima",
  indic_aggregators = "mean",
  target_lags = 1,
  h = 4,
  se = TRUE,
  bootstrap = list(N = 40, block_length = NULL)
)

forecast(uncertainty_model)
summary(uncertainty_model)
plot(uncertainty_model, type = "forecast")

