Write the code for this in R for a 5 series using Y, I am doing price discovery forgeneralized information share (GIS) and Gonzalo and Granger permanent-temporary decomposition (PT-GG) based information share measures for the spot, futures, and three ETFs.
where β and α are n×(n−1) matrices of rank n−1. The columns of β consist of the n−1 cointegrating vectors, and each column of α consists of the adjustment coefficients. The matrix Π is decomposed in such a way that βTYt represents the vector of n−1 stationary series. Let Ω denote the n×n covariance matrix of the innovation vector, i.e., E[εtεtT]=Ω. Following Stock and Watson (1988), equation (1) can be transformed into the following two equivalent vector moving average (VMA) representations (Hasbrouck, 1995):
Based on the above representations, Ψ(1)εt represents the long-run impact of innovations on the unit-root series (Hasbrouck, 1995). Different information share measures considered by Hasbrouck (1995), Lien and Shrestha (2009), and Lien and Shrestha (2014) are based on this term.
\textbf{GENERALIZED INFORMATION SHARE (GIS) MEASURES}
Based on the above framework, we first discuss the GIS measure. Note that, in this study, we have five non-stationary series with four cointegrating vectors. Therefore, the cointegrating vector represented by matrix β can be expressed as follows:
In other words, equation (4) implies that the first row of Ψ(1) is equal to the γj−1 times the jth row of Ψ(1). Therefore, the long-run impact of innovations on the ith series is respectively given by
where ψij is the jth element of ψir and Ωij is the (i,j)th element of Ω.
Let Sj,i denote the contribution of the innovation of series j to the total variance of the \textit{long-run impact} of innovation on series i. Then, we have the following:
Note that Sj,i is independent of i. Therefore, the contribution of the innovation of series j to the total variance of the \textit{long-run impact} of innovation on any series will be the same. It is important to note that Sj,i given by equation (9) is valid only when the innovations are independent. However, in general, the innovations are not independent. When the innovations are not independent, we diagonalize the correlation matrix and end up with the GIS measure proposed by Lien and Shrestha (2014). Let Λ be a diagonal matrix containing the eigenvalues of the innovation correlation matrix on the diagonal, where the corresponding eigenvectors are given by the columns of matrix G. Then, we can calculate the information share of the jth series as follows:
where ψ1G=ψ1rFM,FM=[GΛ−1/2GTV−1]−1 and ψjG is the jth element of ψ1G. The information share measure given by equation (10) is referred to as the generalized information share (GIS) measure. It can be shown that the GIS measure is independent of ordering. Therefore, the GIS method leads to a unique information share, unlike the upper and lower bound for Hasbrouck IS measure.
\vspace{1cm}
\textbf{GONZALO-GRANGER PERMANENT TEMPORARY DECOMPOSITION (PT/GG) INFORMATION SHARE}
Here, we briefly describe the PT/GG method. Gonzalo and Granger (1995) propose a way of decomposing the vector of non-stationary series Yt into permanent component ft (non-stationary series) and transitory (stationary) component Y^t, where the identification of these components is achieved by assuming that (i) the permanent component is a linear function of the original series and that (ii) the transitory component does not Granger cause the permanent component in the long-run.
The permanent component ft (under the linearity condition) can be written as:
[
f_t = \mu^T Y_t \tag{11}
]
where μ is an n×1 (or, 5 × 1 in this study) permanent component coefficient vector which can be shown to be orthogonal to the adjustment coefficient matrix α, i.e., μ=α⊥.
In our study, since we have five unit-root series, the permanent component, ft can be represented by:
[
f_t = \mu_1 Y_1 t + \mu_2 Y_2 t + \cdots + \mu_5 Y_5 t \tag{12}
]
If all the elements of μ are non-negative, then the PT/GG based information share of the ith series is given by:
In the case of non-negative μ, its elements correspond to the contribution of individual series to the permanent component. Therefore, the above definition of price discovery makes sense. However, there is no guarantee that all the elements of μ will be non-negative. It is important to note that the negative elements of μ may not necessarily lead to problems. For example, if some of the unit-root processes are negatively related to the common-stochastic trend, we expect the corresponding elements of μ to be negative. In such cases, where the negative elements of μ are valid, we can use the following definition of information share:
However, if some of the elements of μ are unexpectedly negative, one way to compute the PT/GG based information share is to replace the negative elements with zero and use equation (13). However, this will lead to all negative elements having zero information share regardless of their absolute value. Alternatively, we can add a constant number to each element of μ to obtain μ∗ so that the series with the most negative element in μ will have zero information share. This method will result in the following information share measure:
Certainly! Below is a comprehensive R script that performs price discovery for the generalized information share (GIS) and the Gonzalo and Granger permanent-temporary decomposition (PT-GG) based information share measures for your five-series data (log_Spot, log_Fut, log_USO, log_USL, log_OIL). This script follows the methodology outlined in your provided document and includes detailed comments to guide you through each step.
# Load Required Libraries
# Install any missing packages using install.packages("packageName") if necessary
library(urca) # For cointegration analysis
library(vars) # For VAR and VECM models
library(tibble) # For data manipulation
library(dplyr) # For data manipulation
library(matrixcalc) # For null space calculation
library(MASS) # For generalized inverse
# -------------------------------------------------------------
# 1. Data Preparation
# -------------------------------------------------------------
# Assuming `log_data` is your data frame containing the log-transformed series
# and has been loaded into your R environment.
# Select the relevant columns
Y <- log_data[, c("log_Spot", "log_Fut", "log_USO", "log_USL", "log_OIL")]
# Inspect the structure of Y
str(Y)
# -------------------------------------------------------------
# 2. Determine Optimal Lag Length for VAR/VECM
# -------------------------------------------------------------
# Use VARselect to determine the optimal lag length based on information criteria
lag_selection <- VARselect(Y, lag.max = 10, type = "const")
print("Optimal Lag Length Selection:")
print(lag_selection$selection)
# Choose the lag length based on AIC (can be changed to BIC or other criteria)
selected_lag <- lag_selection$selection["AIC(n)"]
print(paste("Selected Lag Length (AIC):", selected_lag))
# -------------------------------------------------------------
# 3. Johansen Cointegration Test
# -------------------------------------------------------------
# Perform the Johansen cointegration test
# type = "trace" uses the trace statistic
# ecdet = "const" includes a constant in the cointegration relation
# spec = "transitory" specifies the transitory dynamics specification
jotest <- ca.jo(Y, type = "trace", ecdet = "const", K = selected_lag, spec = "transitory")
# Summarize the Johansen test results
summary(jotest)
# -------------------------------------------------------------
# 4. Specify the Number of Cointegrating Vectors (r)
# -------------------------------------------------------------
# Based on the summary, decide on the number of cointegrating vectors
# For this example, we'll assume r = 4 as per your description
r <- 4
# -------------------------------------------------------------
# 5. Extract VECM Components (Alpha and Beta)
# -------------------------------------------------------------
# Extract the cointegrating vectors (Beta)
beta <- jotest@V[, 1:r] # Each column represents a cointegrating vector
# Extract the adjustment coefficients (Alpha)
alpha <- jotest@W[, 1:r] # Each column represents an adjustment coefficient vector
# Display Alpha and Beta
print("Alpha (Adjustment Coefficients):")
print(alpha)
print("Beta (Cointegrating Vectors):")
print(beta)
# -------------------------------------------------------------
# 6. Compute the Pi Matrix (Pi = Alpha * Beta')
# -------------------------------------------------------------
Pi <- alpha %*% t(beta)
print("Pi Matrix:")
print(Pi)
# -------------------------------------------------------------
# 7. Convert VECM to VAR Representation
# -------------------------------------------------------------
# Convert the estimated VECM to a VAR representation
vecm_var <- vec2var(jotest, r = r)
# -------------------------------------------------------------
# 8. Compute Psi(1) - Long-Run Impact Matrix
# -------------------------------------------------------------
# Psi(L) = (I - A1 L - A2 L^2 - ...)^{-1}
# To compute Psi(1), we sum the VAR coefficients and invert (I - sum A_i)
# Extract VAR coefficients
A_matrices <- vecm_var$A # List of coefficient matrices for each lag
# Initialize identity matrix
I_mat <- diag(ncol(Y))
# Sum all A_i matrices
A_sum <- matrix(0, nrow = ncol(Y), ncol = ncol(Y))
for (i in 1:length(A_matrices)) {
A_sum <- A_sum + A_matrices[[i]]
}
# Compute Psi(1)
Psi1 <- solve(I_mat - A_sum)
print("Psi(1) Matrix:")
print(Psi1)
# -------------------------------------------------------------
# 9. Compute the Covariance Matrix of Innovations (Omega)
# -------------------------------------------------------------
# Extract the residual covariance matrix from the VAR model
Omega <- vecm_var$Sigma.u
print("Covariance Matrix of Innovations (Omega):")
print(Omega)
# Check if Omega is diagonal (indicating independent innovations)
is_diag <- all(abs(Omega - diag(diag(Omega))) < 1e-6)
print(paste("Is Omega diagonal (independent innovations)?", is_diag))
# -------------------------------------------------------------
# 10. Calculate Generalized Information Share (GIS)
# -------------------------------------------------------------
if (is_diag) {
# Innovations are independent
# Compute S_j using equation (9):
# S_j = (Psi1[1, j]^2 * Omega[j,j]) / sum_j (Psi1[1,j]^2 * Omega[j,j])
numerator <- (Psi1[1, ]^2) * diag(Omega)
denominator <- sum(numerator)
S_j <- numerator / denominator
} else {
# Innovations are not independent
# Perform eigen-decomposition of Omega
eigen_Omega <- eigen(Omega)
Lambda <- diag(eigen_Omega$values)
G <- eigen_Omega$vectors
# Compute F^M as per equation (10)
# F_M = [G * Lambda^{-1/2} * G' * V^{-1}]^{-1}
# where V = Psi1 * Omega * Psi1'
V <- Psi1 %*% Omega %*% t(Psi1)
# Ensure Lambda is invertible
if(any(eigen_Omega$values <= 0)) {
stop("Omega has non-positive eigenvalues, cannot compute Lambda^{-1/2}.")
}
Lambda_inv_sqrt <- solve(sqrt(Lambda))
F_M <- solve(G %*% Lambda_inv_sqrt %*% t(G) %*% solve(V))
# Compute Psi1^G
Psi1_G <- Psi1 %*% F_M
# Compute S_j^G using equation (10):
# S_j^G = (Psi1_G[j]^2) / (Psi1 * Omega * Psi1')
numerator <- Psi1_G[1, ]^2
denominator <- Psi1 %*% Omega %*% t(Psi1)
S_j <- numerator / denominator[1, 1]
}
# Create a DataFrame for GIS
GIS_df <- data.frame(
Series = colnames(Y),
GIS = S_j
)
print("Generalized Information Share (GIS):")
print(GIS_df)
# -------------------------------------------------------------
# 11. Compute Gonzalo-Granger Permanent-Temporary (PT-GG) Information Share
# -------------------------------------------------------------
# The PT-GG method requires identifying the permanent component coefficients (mu)
# mu is orthogonal to the adjustment coefficients (alpha)
# Compute the null space of Alpha to find mu
# Using matrixcalc::nullspace which returns a matrix whose columns form a basis for the null space
mu_matrix <- nullspace(alpha)
# Since we have r = 4 cointegrating vectors for n = 5 series,
# the null space should be of dimension 1
mu <- mu_matrix[,1]
# Normalize mu to ensure sum(mu) = 1 (optional, for interpretability)
mu <- mu / sum(mu)
# Check for non-negativity
if(all(mu >= 0)) {
# If all elements are non-negative, proceed normally
PTGG <- mu / sum(mu) # Ensures the shares sum to 1
} else {
# If there are negative elements, adjust as per equation (14) or (15)
# Option 1: Use absolute values
PTGG_positive <- abs(mu)
PTGG <- PTGG_positive / sum(PTGG_positive)
# Option 2: Add a constant to make all elements non-negative
# Uncomment the following lines if you prefer this method
# min_mu <- min(mu)
# if(min_mu < 0){
# mu_star <- mu + abs(min_mu)
# } else {
# mu_star <- mu
# }
# PTGG <- mu_star / sum(mu_star)
}
# Create a DataFrame for PT-GG Information Share
PTGG_df <- data.frame(
Series = colnames(Y),
PTGG = PTGG
)
print("Gonzalo-Granger PT/GG Information Share:")
print(PTGG_df)
# -------------------------------------------------------------
# 12. Summary of Results
# -------------------------------------------------------------
# Combine GIS and PTGG into a single table for comparison
information_share <- GIS_df %>%
left_join(PTGG_df, by = "Series")
print("Comparison of GIS and PT-GG Information Share Measures:")
print(information_share)
Explanation of the Script
Loading Libraries: The script begins by loading the necessary R libraries. Ensure all these packages are installed in your R environment. If not, you can install them using install.packages("packageName").
Data Preparation: The data frame log_data is assumed to contain your log-transformed series. Replace log_data with your actual data frame if it's named differently. The script selects the five relevant columns for analysis.
Lag Selection: Using the VARselect function from the vars package, the script determines the optimal number of lags to include in the VAR/VECM model based on the Akaike Information Criterion (AIC). You can change the criterion to BIC or another if preferred.
Johansen Cointegration Test: The ca.jo function from the urca package performs the Johansen cointegration test. The script assumes that there are four cointegrating vectors (r = 4) based on your description. Adjust this number based on the test results if necessary.
Extracting VECM Components: The script extracts the cointegrating vectors (beta) and the adjustment coefficients (alpha) from the Johansen test results. These are essential for forming the Pi matrix and later calculations.
Pi Matrix: The Pi matrix is computed as the product of alpha and the transpose of beta.
Converting VECM to VAR: Using the vec2var function, the script converts the estimated VECM to a VAR representation. This is necessary for computing the Psi(1) matrix, which represents the long-run impact of innovations.
Computing Psi(1): Psi(1) is calculated as the inverse of (I - sum of VAR coefficients). This matrix is crucial for both GIS and PT-GG calculations.
Covariance Matrix of Innovations (Omega): The script extracts the residual covariance matrix from the VAR model to determine if the innovations are independent. If Omega is diagonal, it implies independent innovations; otherwise, innovations are correlated.
Generalized Information Share (GIS):
Independent Innovations: If Omega is diagonal, GIS is computed using equation (9), which involves the square of Psi(1) elements multiplied by the diagonal elements of Omega.
Notes and Recommendations
Data Integrity: Ensure that your log_data does not contain missing values (NA). If there are missing values, handle them appropriately before running the analysis.
Interpretation of Results: The GIS and PT-GG measures provide insights into the contribution of each series to the long-term price discovery process. Higher values indicate a more significant role in price discovery.
Model Assumptions: The VECM assumes that the underlying series are non-stationary and cointegrated. Ensure that these assumptions hold for your data. You can perform unit root tests (e.g., Augmented Dickey-Fuller) and additional cointegration tests as needed.
Customization: Depending on the characteristics of your data, you might need to adjust the lag length, the specification of deterministic terms, or other model parameters.
Error Handling: The script includes basic error handling, especially when dealing with non-diagonal Omega matrices. Ensure that Omega is positive definite before performing inversions.
Further Analysis: After obtaining the information share measures, consider visualizing them or conducting robustness checks to validate your findings.
Example Output
After running the script, you should obtain outputs similar to the following (values are illustrative):
Generalized Information Share (GIS):
Series GIS
1 log_Spot 0.2500000
2 log_Fut 0.2500000
3 log_USO 0.2500000
4 log_USL 0.1500000
5 log_OIL 0.1000000
Gonzalo-Granger PT/GG Information Share:
Series PTGG
1 log_Spot 0.300000
2 log_Fut 0.250000
3 log_USO 0.200000
4 log_USL 0.150000
5 log_OIL 0.100000
Comparison of GIS and PT-GG Information Share Measures:
Series GIS PTGG
1 log_Spot 0.2500000 0.300000
2 log_Fut 0.2500000 0.250000
3 log_USO 0.2500000 0.200000
4 log_USL 0.1500000 0.150000
5 log_OIL 0.1000000 0.100000
These values indicate how each series contributes to the price discovery process under both GIS and PT-GG methodologies.
Feel free to customize and extend this script based on your specific requirements and data characteristics. If you encounter any issues or have further questions, don't hesitate to ask!
Dependent Innovations: If Omega is not diagonal, the script performs eigen-decomposition, calculates F_M, and then computes GIS using equation (10).
Gonzalo-Granger PT/GG Information Share:
The script computes the permanent component coefficients (mu) by finding the null space of the alpha matrix.
If all elements of mu are non-negative, it normalizes them to sum to one.
If there are negative elements, it adjusts them by taking absolute values before normalization (as per equation (14)). Alternatively, you can uncomment the provided lines to add a constant and make all elements non-negative, following equation (15).
Summary of Results: Finally, the script combines GIS and PT-GG measures into a single table for easy comparison.