Certainly! Below is a comprehensive R script that performs price discovery for the Generalized Information Share (GIS) using a Vector Error Correction Model (VECM) on your 5-series dataset (Y). This script follows these main steps:
- Loading Necessary Libraries: Essential R packages for time series analysis and cointegration testing.
- Data Preparation: Handling missing values and converting the data into a time series object.
- Stationarity Testing: Ensuring that each series is integrated of the same order, typically I(1).
- Cointegration Testing: Using the Johansen test to determine the number of cointegrating relationships.
- Fitting the VECM: Estimating the VECM parameters based on the cointegration results.
- Extracting VECM Components: Obtaining the adjustment coefficients (
alpha), cointegrating vectors (beta), and the matrix Π.
- (Optional) Calculating Generalized Information Shares: Depending on your specific GIS methodology, this step may vary.
Here's the detailed R code with explanations at each step:
# ================================================
# Price Discovery for Generalized Information Share (GIS)
# Using Vector Error Correction Model (VECM) in R
# ================================================
# 1. Load Necessary Libraries
# ----------------------------
# Install packages if not already installed
required_packages <- c("tidyverse", "urca", "vars", "tsDyn", "lubridate")
installed_packages <- installed.packages()
for (pkg in required_packages) {
if (!pkg %in% rownames(installed_packages)) {
install.packages(pkg)
}
}
# Load libraries
library(tidyverse)
library(urca)
library(vars)
library(tsDyn)
library(lubridate)
# 2. Data Preparation
# --------------------
# Assuming 'log_data' is your data frame containing the log-transformed series
# with columns: "log_Spot", "log_Fut", "log_USO", "log_USL", "log_OIL"
# Extract the relevant columns
Y <- log_data[, c("log_Spot", "log_Fut", "log_USO", "log_USL", "log_OIL")]
# Inspect the structure
str(Y)
# Handle missing values by omitting them
# This removes any rows with NA values
Y_clean <- na.omit(Y)
# Convert to time series object
# Assuming the data is daily with 252 trading days per year
# Adjust 'start' and 'frequency' as per your data's actual time frame
Y_ts <- ts(Y_clean, frequency = 252, start = c(YYYY, MM)) # Replace YYYY and MM with start year and month
# 3. Stationarity Testing
# ------------------------
# It's essential to ensure that all series are integrated of the same order, typically I(1)
# Perform Augmented Dickey-Fuller (ADF) tests
adf_results <- lapply(colnames(Y_ts), function(series) {
adf_test <- ur.df(Y_ts[, series], type = "drift", selectlags = "AIC")
summary(adf_test)
})
# Print ADF test results
for (i in 1:length(adf_results)) {
cat("ADF Test for", colnames(Y_ts)[i], ":\n")
print(adf_results[[i]])
cat("\n-------------------------------\n")
}
# If any series is not I(1), consider differencing or transforming appropriately
# 4. Cointegration Testing
# -------------------------
# Determine the optimal lag length for the VECM
lag_selection <- VARselect(Y_ts, lag.max = 10, type = "const")
print(lag_selection$selection)
# Choose the lag order based on AIC or BIC
optimal_lag <- lag_selection$selection["AIC(n)"]
cat("Optimal lag length selected by AIC:", optimal_lag, "\n")
# Perform Johansen Cointegration Test
# 'type' can be "trace" or "eigen"; here we use "trace"
# 'ecdet' specifies deterministic components; "const" includes a constant term
johansen_test <- ca.jo(Y_ts, type = "trace", ecdet = "const", K = optimal_lag)
# Summary of Johansen Test
summary(johansen_test)
# Determine the number of cointegrating relationships (rank)
rank <- johansen_test@rank
cat("Number of cointegrating relationships:", rank, "\n")
# 5. Fitting the VECM
# --------------------
# Fit the VECM using the Johansen results
vecm_model <- cajorls(johansen_test, r = rank)
print(vecm_model$rlm) # Display the Restricted Least Squares estimates
# Alternatively, using the 'vars' package to fit VECM
# Note: The 'vars' package handles VECM implicitly through VAR representation
var_model <- VAR(Y_ts, p = optimal_lag, type = "const")
vecm_fit <- cajorls(johansen_test, r = rank)
# 6. Extracting VECM Components
# ------------------------------
# Extract adjustment coefficients (alpha) and cointegrating vectors (beta)
alpha <- johansen_test@V[, 1:rank] # Adjustment coefficients
beta <- johansen_test@W[, 1:rank] # Cointegrating vectors
# Compute the Π matrix (Pi = alpha %*% t(beta))
Pi <- alpha %*% t(beta)
# Display the Pi matrix
print("Matrix Π (Pi):")
print(Pi)
# 7. (Optional) Calculating Generalized Information Shares (GIS)
# ---------------------------------------------------------------
# The calculation of GIS depends on the specific methodology you're following.
# Typically, it involves analyzing the impact of shocks in the VECM framework.
# Here's a skeleton for computing impulse responses, which can be adapted for GIS.
# Compute Impulse Response Functions (IRFs)
irf_results <- irf(var_model, n.ahead = 10, impulse = NULL, response = NULL, boot = TRUE)
# Plot IRFs
plot(irf_results)
# To calculate GIS, you may need to analyze the contribution of each series to the variance of others
# This often involves variance decomposition or other advanced techniques
# Refer to relevant literature (Hasbrouck, Lien & Shrestha) for the exact computation
# Example: Variance Decomposition
fevd_results <- fev(var_model, n.ahead = 10)
print(fevd_results)
# ================================================
# End of Script
# ================================================
Detailed Explanation:
-
Loading Libraries:
tidyverse: For data manipulation and visualization.
urca: For unit root and cointegration tests.
vars: For Vector Autoregression and related models.
tsDyn: For advanced time series models, including VECM.
lubridate: For easier handling of dates (if needed).
-
Data Preparation:
- Extract the relevant columns from your dataset.
- Use
na.omit() to remove any rows with missing values to ensure a clean time series.
- Convert the data frame to a time series object (
ts). Adjust the start parameter based on your dataset's actual starting date.
-
Stationarity Testing:
- It's crucial that all series are integrated of the same order (preferably I(1)) for cointegration analysis.
- The Augmented Dickey-Fuller (ADF) test is performed on each series to check for stationarity.
- If any series is non-stationary, consider differencing or other transformations.
-
Cointegration Testing:
- Use the Johansen test (
ca.jo) from the urca package to detect cointegrating relationships among the series.
- Determine the optimal lag length using criteria like AIC or BIC with
VARselect.
- The test will help identify how many stable, long-term relationships exist between your variables.
-
Fitting the VECM:
- Once the number of cointegrating relationships is known, fit the VECM using
cajorls.
- The
VECM captures both short-term dynamics and long-term equilibrium relationships.
-
Extracting VECM Components:
alpha: Adjustment coefficients that show how each variable responds to deviations from the long-term equilibrium.
beta: Cointegrating vectors that define the long-term relationships between the variables.
Π (Pi): The product of alpha and , representing the speed of adjustment towards equilibrium.
Additional Notes:
-
Time Series Frequency: Ensure that the frequency parameter in the ts function matches your data's actual frequency (e.g., daily, monthly).
-
Lag Selection: Choosing the correct lag length is vital for model accuracy. While AIC is commonly used, you might also consider other criteria like BIC or HQIC based on your specific needs.
-
Visualization: Plotting IRFs and FEVDs can provide intuitive insights into how shocks affect each series over time.
-
GIS Calculation: Depending on your GIS approach, further customization of the code may be necessary. Review the relevant literature to tailor the computations accordingly.
This script provides a solid foundation for performing VECM-based price discovery analysis. Make sure to adjust parameters like the starting date, frequency, and lag order based on your dataset's specifics. Additionally, consult relevant econometric literature to refine the GIS calculations as per your research requirements.