---
title: "Introduction to kardl"
author: "Huseyin karamelikli and Huseyin Utku Demir"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
 %\VignetteIndexEntry{Introduction to kardl}
 %\VignetteEngine{knitr::rmarkdown}
 %\VignetteEncoding{UTF-8}
---



```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE, message = FALSE, warning = FALSE, fig.width = 16,
  fig.height = 8,
  out.width = "100%",
  dpi = 150
)
```

## Introduction

The `kardl` package is an R tool for estimating symmetric and asymmetric Autoregressive Distributed Lag (ARDL) and Nonlinear ARDL (NARDL) models, designed for econometricians and researchers analyzing cointegration and dynamic relationships in time series data. It offers flexible model specifications, allowing users to include deterministic variables, asymmetric effects for short- and long-run dynamics, and trend components. The package supports customizable lag structures, model selection criteria (AIC, BIC, AICc, HQ), and parallel processing for computational efficiency. Key features include:

- **Flexible Formula Specification**: Use `asymmetric()`, `lasymmetric()`, and `sasymmetric()` to model asymmetric effects in short- and long-run dynamics, and `deterministic()` for dummy variables.
- **Lag Optimization**: Choose between automatic lag selection (`"quick"`, `"grid"`, `"grid_custom"`) or user-defined lags.
- **Dynamic Analysis**: Compute long-run coefficients, perform cointegration tests (PSS F, PSS t, Narayan), and ECM estimation.


This vignette demonstrates how to use the `kardl()` function to estimate an asymmetric ARDL model, perform diagnostic tests, and visualize results, using economic data from Turkey.

```{r srr-tags, eval = FALSE, echo = FALSE}
#' srr tags for the kardl package
#'
#' This package follows structured statistical reporting rules using the
#' \code{srrstats} framework. The standards governing implementation and
#' documentation are summarized below.
#'
#' @srrstats {G1.0} The package documentation and accompanying materials cite
#'           the ARDL bounds-testing and nonlinear ARDL literature on which the
#'           implemented estimators, asymmetry decomposition, bounds tests, and
#'           dynamic multipliers are based.
#' @srrstats {G1.1} The package is described as an implementation and extension
#'           of ARDL and NARDL workflows, supporting mixed symmetric and
#'           asymmetric regressors, flexible lag selection, and dynamic
#'           multiplier methods.
#' @srrstats {G1.2} The README, NEWS file, and package website describe the
#'           development status, recent changes, and future maintenance plans
#'           of the package.
#' @srrstats {G1.3} Key statistical concepts such as ARDL, NARDL, ECM, bounds
#'           testing, short-run asymmetry, long-run asymmetry, and dynamic
#'           multipliers are defined in function documentation and vignettes.
#' @srrstats {G1.4} All user-facing functions and S3 methods are documented
#'           using \code{roxygen2}, and the generated Rd files are maintained
#'           as part of the package documentation workflow.
#' @srrstats {G1.4a} Internal helper functions are documented where necessary
#'           and are excluded from the public help index using \code{@noRd}
#'           or marked as internal.
```


## Installation


`kardl` in R can easily be installed from its CRAN repository:

```{r install-cran, eval=FALSE}
install.packages("kardl")
library(kardl)
```

Alternatively, you can use the `devtools` package to load directly from GitHub:

```{r install, eval=FALSE}
# Install required packages
install.packages(c(
  "stats", "msm", "lmtest", "nlWaldTest", "car", "strucchange",
  "utils", "ggplot2"
))
# Install kardl from GitHub
install.packages("devtools")
devtools::install_github("karamelikli/kardl")
```

Load the package:

```{r load}
library(kardl)
```

## Unique Features and Methodological Contributions

The `kardl` package implements several methodological extensions and improvements for ARDL/NARDL modelling that go beyond standard implementations available in R and other software:

- **different_asym_lag** option: Enables different lag orders for the positive and negative partial sum decompositions in NARDL models. This provides greater flexibility than the common symmetric lag restriction used in most existing packages.
- **Narayan cointegration test** (`narayan()`): A dedicated small-sample bounds test (Narayan, 2005) with automatic handling of critical values for cases II–V. While the test exists in the literature, its seamless integration into a full ARDL/NARDL workflow is unique in R.
- **Symmetry tests** (`symmetrytest()`): Comprehensive Wald tests for both short-run and long-run symmetry in NARDL models.
- **Bootstrap confidence intervals for dynamic multipliers**: Robust uncertainty quantification around short-run, long-run, and impact multipliers through resampling methods, fully integrated with asymmetric multiplier estimation.
- Additional advanced capabilities include highly flexible formula parsing for mixed symmetric/asymmetric regressors, multiple model selection criteria (AIC, BIC, AICc, HQ), parallel processing support, and extensive post-estimation tools tailored for asymmetric analysis.

These features make `kardl` particularly suitable for researchers needing fine-grained control over asymmetric dynamics and small-sample inference.


## Estimating an asymmetric ARDL Model

This example estimates an asymmetric ARDL model to analyze the impact of petrol prices and driving patterns on road fatalities in the UK, using the built-in `Seatbelts` dataset with variables for DriversKilled, PetrolPrice, drivers, kms, and a seatbelt law dummy variable.

### Step 1: Data Preparation

The `Seatbelts` dataset contains monthly data on road casualties in Great Britain from 1969 to 1984. We convert it to a data frame for analysis.

Note: The `Seatbelts` dataset is a built-in R dataset included in the `datasets` package.
The data can be accessed directly by converting the time series object to a data frame.


### Step 2: Define the Model Formula

We define the model formula using R's formula syntax, incorporating asymmetric effects and deterministic variables. We use `asymmetric()` for variables with both short- and long-run asymmetry, `lasymmetric()` for long-run asymmetry, `sasymmetric()` for short-run asymmetry, and `deterministic()` for fixed dummy variables. The `trend` term includes a linear time trend in the model.

```{r data-prepare}
# Define the model formula
my_formula <- DriversKilled ~ PetrolPrice + drivers +
  asymmetric(PetrolPrice + drivers) + deterministic(law) + trend
```
Indeed, the formula syntax is flexible, allowing for various combinations of asymmetric and deterministic variables. The following variations of the formula are equivalent and will yield the same model specification:

```{r eval=FALSE}
same_formula <- y ~ asymmetric(x1) +
  sasymmetric(x2 + x3) +
  lasymmetric(x4 + x5) +
  deterministic(dummy1) + trend
same_formula <- y ~ asymmetric(x1) +
  sasymmetric(x2 + x3) +
  lasymmetric(x4 + x5) +
  deterministic(dummy1) + trend
same_formula <- y ~ asym(x1) + sasym(x2 + x3) + lasym(x4 + x5) +
  det(dummy1) + trend
same_formula <- y ~ a(x1) + s(x2 + x3) + l(x4 + x5) + d(dummy1) + trend
```




### Step 3: Model Estimation

We estimate the ARDL model using different `mode` settings to demonstrate flexibility in lag selection. The `kardl()` function supports various modes: `"grid"`, `"grid_custom"`, `"quick"`, or a user-defined lag vector.

#### Using `mode = "grid"`
The `"grid"` mode evaluates all lag combinations up to `maxlag` and provides console feedback.

```{r model-grid}
# Set model options
kardl_set(criterion = "BIC", different_asym_lag = TRUE, data = Seatbelts)
# Estimate model with grid mode
kardl_model <- kardl(
  data = Seatbelts, formula = my_formula,
  maxlag = 4, mode = "grid"
)
# View results
kardl_model
```
Summary of the model provides detailed information about the estimated coefficients, standard errors, t-values, and significance levels.

```{r model-grid-custom-summary}
# Display model summary
summary(kardl_model)
```


#### Using User-Defined Lags

Specify custom lags to bypass automatic lag selection:

```{r model-user-defined}
kardl_model2 <- kardl(
  data = Seatbelts, my_formula,
  mode = c(2, 1, 1, 3, 0)
)
# View results
kardl_extract(kardl_model2, "opt_lag")
```
```{r model-user-defined-summary}
# Display model summary
summary(kardl_model2)
```



#### Using All Variables
Use the `.` operator to include all variables except the dependent variable:

```{r model-all-vars}
kardl_set(data = Seatbelts)
kardl(formula = DriversKilled ~ . + deterministic(law), maxlag = 2)
```

#### Visualizing Lag Criteria

The `lag_criteria` component contains lag combinations and their criterion values. We visualize these to compare model selection criteria (AIC, BIC, HQ).

```{r lag-criteria}
library(dplyr)
library(tidyr)
library(ggplot2)
# Convert lag_criteria to a data frame
lag_criteria <- as.data.frame(kardl_extract(kardl_model, "lag_criteria"))
lag_criteria <- lag_criteria |> mutate(across(c(AIC, BIC, HQ), as.numeric))

# Pivot to long format
lag_criteria_long <- lag_criteria |>
  select(-c(AICc, AdjR2)) |>
  pivot_longer(
    cols = c(AIC, BIC, HQ),
    names_to = "Criteria",
    values_to = "Value"
  )

# Find minimum values
min_values <- lag_criteria_long |>
  group_by(Criteria) |>
  slice_min(order_by = Value) |>
  ungroup()

# Plot
ggplot(
  lag_criteria_long,
  aes(x = lag, y = Value, color = Criteria, group = Criteria)
) +
  geom_line() +
  geom_point(
    data = min_values, aes(x = lag, y = Value),
    color = "red", size = 3, shape = 8
  ) +
  geom_text(
    data = min_values, aes(x = lag, y = Value, label = lag),
    vjust = 1.5, color = "black", size = 3.5
  ) +
  scale_x_discrete(
    breaks = lag_criteria$lag[seq(1, nrow(lag_criteria), by = 20)]
  ) +
  labs(
    title = "Lag Criteria Comparison",
    x = "Lag Configuration",
    y = "Criteria Value"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
```

#### Error Correction Model (ECM) Estimation

The `ecm()` function estimates a Restricted ECM for cointegration testing. We specify the same formula and lag structure as in the ARDL model.
```{r ecm-estimation}
ecm_model <- ecm(
  data = Seatbelts, formula = my_formula,
  maxlag = 4, mode = "grid_custom"
)
# View results
summary(ecm_model)
```


### Step 4: Long-Run Coefficients

We calculate long-run coefficients using `kardl_longrun()`, which standardizes coefficients by dividing them by the negative of the dependent variable’s long-run parameter.

```{r long-run}
# Long-run coefficients
my_long <- kardl_longrun(kardl_model)
my_long
```

The `summary()` function provides detailed information about the long-run coefficients, including standard errors, t-values, and significance levels.

```{r long-run-summary}
# Summary of long-run coefficients
summary(my_long)
```


### Step 5: Symmetry Test

The `symmetrytest()` function performs Wald tests to assess short- and long-run asymmetry in the model.

```{r asymmetry-test}
ast <- Seatbelts |>
  kardl(
    DriversKilled ~ PetrolPrice + drivers + asymmetric(PetrolPrice + drivers) +
      deterministic(law) + trend,
    mode = c(1, 2, 3, 0, 1),
    data = _
  ) |>
  symmetrytest()
ast
```

Summary of the symmetry test provides detailed results for both long-run and short-run asymmetry tests, including F-values, p-values, hypotheses, and test decisions.

```{r asymmetry-test-summary}
# Summary of symmetry test
summary(ast)
```



### Step 6: Cointegration Tests

We perform cointegration tests to assess long-term relationships using `pssf()`, `psst()`, and `narayan()`.

#### PSS F Bound Test

The `pssf()` function tests for cointegration using the Pesaran, Shin, and Smith F Bound test.

```{r pssf}
test_result <- kardl_model |> pssf(case = 3, signif_level = "0.05")
test_result
```

Summary of the PSS F Bound test provides detailed information about the test statistic, critical values, hypotheses, and decision regarding cointegration.

```{r pssf-summary}
summary(test_result)
```

#### PSS t Bound Test

The `psst()` function tests the significance of the lagged dependent variable’s coefficient.

```{r psst}
test_result <- kardl_model |> psst(case = 3, signif_level = "0.05")
test_result
```
Summary of the PSS t Bound test provides detailed information about the test statistic, critical values, hypotheses, and decision regarding cointegration.
```{r psst-summary}
summary(test_result)
```

#### Narayan Test

The `narayan()` function is tailored for small sample sizes. It tests for cointegration using critical values optimized for small samples.

```{r narayan}
test_result <- kardl_model |> narayan(case = 3, signif_level = "0.05")
test_result
```
Summary of the Narayan test provides detailed information about the test statistic, critical values, hypotheses, and decision regarding cointegration.

```{r narayan-summary}
summary(test_result)
```



### Step 7: Dynamic Multipliers

The `mplier()` function calculates dynamic multipliers for the model, showing how changes in independent variables affect the dependent variable over time.
```{r dynamic-multipliers}
multipliers <- kardl_model |> mplier()
# View multipliers of the model
head(kardl_extract(multipliers, "multipliers"))
# View long-run multipliers
kardl_extract(multipliers, "omega")
# View short-run multipliers
head(kardl_extract(multipliers, "lambda"))
```

Plotting dynamic multipliers for specific variables can be done using the `plot()` function, which visualizes the response of the dependent variable to changes in independent variables over time.
```{r plot-multipliers}
plot(multipliers, variables = c("PetrolPrice", "drivers"))
```

 
 To handle a large number of variables, you can specify a subset of variables to plot or use `variables = "all"` to visualize all dynamic multipliers.
 
 Bootstrap confidence intervals for dynamic multipliers can be calculated using the `bootstrap()` function, which provides robust estimates of uncertainty around the multipliers.
```{r bootstrap-multipliers}
bootstrap_results <- kardl_model |>
  bootstrap(horizon = 12, replications = 10)
# View bootstrap summary
summary(bootstrap_results)
```

Visualize bootstrap results for specific variables to understand the variability and confidence intervals of the dynamic multipliers.

```{r plot-bootstrap-multipliers}
plot(bootstrap_results, variables = "drivers")
```
 


### Step 8: Customizing asymmetric Variables

We demonstrate how to customize prefixes and suffixes for asymmetric variables using `kardl_set()`.

```{r asym-custom}
# Set custom prefixes and suffixes
kardl_reset()
kardl_set(asym_prefix = c("asyP_", "asyN_"), asym_suffix = c("_PP", "_NN"))
kardl_custom <- kardl(data = Seatbelts, my_formula)
kardl_custom
```

## Key Functions and Parameters

- **`kardl(data, model, maxlag, mode, ...)`**:
  - `data`: A time series dataset (e.g., a data frame with DriversKilled, PetrolPrice, drivers).
  - `formula`: A formula specifying the long-run equation, e.g., `y ~ x + z + asymmetric(z) + lasymmetric(x2 + x3) + sasymmetric(x3 + x4) + deterministic(dummy1 + dummy2) + trend`. Supports:
    - `asymmetric()`: asymmetric effects for both short- and long-run dynamics.
    - `lasymmetric()`: Long-run asymmetric variables.
    - `sasymmetric()`: Short-run asymmetric variables.
    - `deterministic()`: Fixed dummy variables.
    - `trend`: Linear time trend.
  - `maxlag`: Maximum number of lags (default: 4). Use smaller values (e.g., 2) for small datasets, larger values (e.g., 8) for long-term dependencies.
  - `mode`: Estimation mode:
    - `"quick"`: Verbose output for interactive use.
    - `"grid"`: Verbose output with lag optimization.
    - `"grid_custom"`: Silent, efficient execution.
    - User-defined vector (e.g., `c(1, 2, 4, 5)` or `c(DriversKilled = 2, PetrolPrice_POS = 3, PetrolPrice_NEG = 1, drivers = 3)`).
  - Returns a list with components: `inputs`, `finalModel`, `start_time`, `end_time`, `properLag`, `time_span`, `opt_lag`, `lag_criteria`, `type` ("kardlmodel").

- **`kardl_set(...)`**: Configures options like `criterion` (AIC, BIC, AICc, HQ), `different_asym_lag`, `asym_prefix`, `Sasymuffix`, `short_coef`, and `long_coef`. Use `kardl_get()` to retrieve settings and `kardl_reset()` to restore defaults.

- **`kardl_longrun(model)`**: Calculates standardized long-run coefficients, returning `type` ("kardl_longrun"), `coef`, `delta_se`, `results`, and `starsDesc`.

- **`symmetrytest(model)`**: Performs Wald tests for short- and long-run asymmetry, returning `Lhypotheses`, `Lwald`, `Shypotheses`, `Swald`, and `type` ("symmetrytest").

- **`pssf(model, case, signif_level)`**: Performs the Pesaran, Shin, and Smith F Bound test for cointegration, supporting cases 1–5 and significance levels ("auto", 0.01, 0.025, 0.05, 0.1, 0.10).

- **`psst(model, case, signif_level)`**: Performs the PSS t Bound test, focusing on the lagged dependent variable’s coefficient.

- **`narayan(model, case, signif_level)`**: Conducts the Narayan test for cointegration, optimized for small samples (cases 2–5).

- **`ecm(data, model, maxlag, mode,  ...)`**: Conducts the Restricted ECM test for cointegration, with similar parameters to `kardl()` and case/significance level options.

For detailed documentation, use `?kardl`, `?kardl_set`, `?kardl_longrun`, `?symmetrytest`, `?pssf`, `?psst`, `?narayan`, or `?ecm`.

## Conclusion

The `kardl` package is a versatile tool for econometric analysis, offering robust support for symmetric and asymmetric ARDL/NARDL modeling, cointegration tests, stability diagnostics, and heteroskedasticity checks. Its flexible formula specification, lag optimization, and support for parallel processing make it ideal for studying complex economic relationships. For more information, visit [https://github.com/karamelikli/kardl](https://github.com/karamelikli/kardl) or contact the authors at [hakperest@gmail.com](mailto:hakperest@gmail.com).

---
