---
title: "<span style='font-size:24px;'>Analyzing the Correlation Between Daily WTI and Brent Crude Oil Prices (1995-2020)</span>"
output:
  html_document: 
    code_download: true
    highlight: zenburn
    toc_depth: 4
    df_print: kable
    theme: lumen
date: "November 03, 2024"
editor_options: 
  markdown: 
    wrap: 72
---

#### *Submitted to:* $Joseph DeCoste_{Assistant Professor}$
<br>
<style type="text/css"> body, td {font-size: 15px;} code.r{font-size: 15px;} pre {font-size: 15px} </style>
<script src="https://code.jquery.com/jquery-3.7.1.slim.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
  $('a').attr('target', '_blank');
  });
</script>
<style>
.boxed {
  background: #1C1C1C;
  color: #ffffff;
  border: 0px solid #646464;
  margin: 0px auto;
  width: auto;
  padding: 10px;
  border-radius: 0px;
}
</style>


#  {.tabset}



## Assignment #3

<p>**Context:** </p>
<p>You are the head of trading at a large Canadian integrated oil and gas firm. Your job is to manage spot and futures positions in oil and gas to ensure a balanced inventory, sell the companies raw and refined products, and manage the companies oil price risk. The oil your company produces is benchmarked to West Texas Intermediate (WTI), a North American centric oil benchmark, with some adjustments for quality and location differences. </p>
<p>The firms CEO and board would like to further understand whether events in oil markets outside of North America pose a risk to their firm. They would also like to know whether the trading desk could boost its profit by trading non-WTI contracts. </p>
<p>You have been asked to prepare a brief report outlining the relationship between the price of WTI, and the price of Brent (the primary Global oil price benchmark).</p>
<br>
<p>**Assignment:** </p>
<p>Within the above context, write a report suitable for sharing with the CEO and board on the relationship between daily WTI and Brent Crude Oil prices from **1995-01-01** to **2020-12-31**.</p>
<p>**Brent Oil Spot Price:** Crude Oil Prices: Brent - Europe</p>
<p>**WTI Oil Spot Price:** Crude Oil Prices: West Texas Intermediate (WTI) - Cushing, Oklahoma</p>



## Q1. 

**Statistical Analysis**
<br>
<div class="boxed">

A full descriptive table of your time series variables.\
This includes # of observations, # of missing values, mean, median, standard deviation, skewness, and kurtosis. Discuss and compare any notable statistical features of your variables.
</div>


```{r setup, include=FALSE}
knitr::opts_chunk$set(
	echo = TRUE,
	message = FALSE,
	warning = FALSE
)
```

<!-- # Load necessary libraries -->
```{r message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
library(tidyquant)
library(dplyr)
library(ggplot2)
library(moments)
library(tibble)
library(tidyr)
library(vars)
library(knitr)
library(kableExtra)
library(plotly)
library(gridExtra)
library(tseries)
```


```{r message=FALSE, warning=FALSE, paged.print=FALSE}
start_date <- "1995-01-01"
end_date <- "2020-12-31"
```

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# Retrieve WTI Crude Oil Prices
wti_data <- tq_get("DCOILWTICO", get = "economic.data", from = start_date, to = end_date)
# Retrieve Brent Crude Oil Prices
brent_data <- tq_get("DCOILBRENTEU", get = "economic.data", from = start_date, to = end_date)
```

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
oil_data <- left_join(wti_data, brent_data, by = "date", suffix = c("_WTI", "_Brent"))
oil_data <- na.omit(oil_data)
```

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
calculate_statistics <- function(data, variable_name) {
  data %>%
    summarise(
      Variable = variable_name,
      Observations = n(),
      Missing_Values = sum(is.na(.data[[variable_name]])),
      Mean = mean(.data[[variable_name]], na.rm = TRUE),
      Median = median(.data[[variable_name]], na.rm = TRUE),
      Standard_Deviation = sd(.data[[variable_name]], na.rm = TRUE),
      Skewness = skewness(.data[[variable_name]], na.rm = TRUE),
      Kurtosis = kurtosis(.data[[variable_name]], na.rm = TRUE)
    )
}
```

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
wti_stats <- calculate_statistics(oil_data, "price_WTI")
brent_stats <- calculate_statistics(oil_data, "price_Brent")

# results in a single table
descriptive_table <- bind_rows(wti_stats, brent_stats)
descriptive_table %>%
  kable(
    format = "html",            
    caption = "Descriptive Statistics of Oil Prices",
    digits = 4                  
  ) %>%
  kable_styling(
    bootstrap_options = c("striped", "hover", "condensed"),
    full_width = FALSE,
    position = "center"
  ) %>% 
row_spec(1)%>%
  row_spec(0, bold = TRUE, background = "#D3D3D3") %>% 
  column_spec(3, color = "red", bold = TRUE)

```

**Analysis:**
<br>

**Observations and Missing Values: **

<p>Both WTI and Brent datasets contain **6,476 observations** with **no** missing values.</p>

<p>**Mean and Median:** The mean and median prices for both WTI and Brent are close, indicating a relatively symmetric distribution of prices over the period analyzed.</p>

<p>**Standard Deviation:** Brent prices exhibit a slightly higher standard deviation compared to WTI, suggesting marginally greater volatility in Brent prices during the study period.</p>

<p>**Skewness:** Both distributions have positive skewness values **(WTI: 0.52, Brent: 0.55)**, indicating a slight rightward skew. This suggests that there were more instances of higher-than-average prices, though the skewness is relatively mild.</p>

<p>**Kurtosis:** Both the WTI and Brent distributions exhibit less pronounced tails than a normal distribution (kurtosis = 3), indicating they are less prone to extreme price fluctuations.</p>

<p>Since these kurtosis values are close to 3 but less than that, their distributions are somewhat similar to a normal distribution but with slightly flatter peaks and less heavy tails.</p>

<p>For financial data like oil prices, these kurtosis values suggest that extreme price changes (spikes or drops) are less frequent compared to distributions with higher kurtosis.</p>

<p>**In summary,** both WTI and Brent crude oil prices exhibit similar statistical characteristics, with slight differences in volatility and skewness. These similarities reflect the interconnected nature of global oil markets, where factors influencing one benchmark often affect the other in a comparable manner.</p>
<br>
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# Calculate correlation
correlation <- cor(oil_data$price_WTI, oil_data$price_Brent)
print(paste("Correlation between WTI and Brent prices:", round(correlation, 2)))
```
<br>
<p>A correlation coefficient of **0.99** between WTI and Brent crude oil prices indicates an exceptionally strong positive linear relationship. This means that as the price of one benchmark increases or decreases, the price of the other tends to move in the same direction to a nearly identical degree.</p>
<br>

**Implications:**
<br>
<p>**Global Market Integration:** The high correlation suggests that WTI and Brent prices are influenced by similar global supply and demand factors, including geopolitical events, economic conditions, and production decisions by major oil-producing countries.</p>
<br>
<p>**Risk Management:** For firms whose operations are tied to WTI pricing, such as those in North America, this strong correlation implies that global events affecting Brent prices are likely to impact WTI prices similarly. Therefore, monitoring international market developments is crucial for effective risk management.</p>
<br>
<p>**Trading Strategies:** The near-identical movement of WTI and Brent prices indicates limited arbitrage opportunities between these two benchmarks. However, during rare periods of divergence—often due to regional supply disruptions or logistical constraints—traders might find opportunities to capitalize on the price differential.</p>
<br>
<p>**In summary,** the **0.99** correlation coefficient underscores the interconnectedness of WTI and Brent crude oil markets, highlighting the importance of a global perspective in oil trading and risk management strategies.</p>
<br>

## Q2

<div class="boxed">

Generate one time series plot containing both WTI and Brent Oil prices over time.\
Compare the patterns in both price series.
</div>

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# Transform the data
oil_data_long <- oil_data %>%
  pivot_longer(cols = starts_with("price"), names_to = "Type", values_to = "Price") %>%
  mutate(Type = recode(Type, price_WTI = "WTI", price_Brent = "Brent"))

# Create the ggplot object
p <- ggplot(oil_data_long, aes(x = date, y = Price, color = Type)) +
  geom_line() +
  scale_color_manual(values = c("WTI" = "#ffde57", "Brent" = "#4584b6")) +
  labs(title = "WTI and Brent Crude Oil Prices (1995-2020)",
       x = "",
       y = "USD per Barrel",
       color = "Crude Oil Type") +
  theme_minimal()

# Make it interactive
interactive_plot <- ggplotly(p)
htmltools::div(interactive_plot, style = "display: flex; justify-content: center;")


```

**Overall trends:**
<p>Both types of oil show a general increase in prices from the late 1990s to around 2008, peaking at over 100 USD per barrel.</p>
<p>After the 2008 peak, there is a sharp decline, followed by fluctuations with a major dip around 2014-2016 and another significant decline in 2020.</p>
<p>**Volatility:** The data exhibits periods of high volatility, particularly between 2000 and 2020, indicating economic and market events that impacted oil prices.</p>

## Q3. 

<div class="boxed">

Convert prices to log prices, use log prices for the remaining analysis
</div>

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# log transformation
oil_data <- oil_data %>%
  mutate(log_price_WTI = log(price_WTI),
         log_price_Brent = log(price_Brent))

# statistics for log-transformed prices
log_wti_stats <- calculate_statistics(oil_data, "log_price_WTI")
log_brent_stats <- calculate_statistics(oil_data, "log_price_Brent")

# results in a single table
log_descriptive_table <- bind_rows(log_wti_stats, log_brent_stats)
log_descriptive_table %>%
  kable(
    format = "html",            
    caption = "Log Descriptive Statistics of Oil Prices",
    digits = 4                  
  ) %>%
  kable_styling(
    bootstrap_options = c("striped", "hover", "condensed"),
    full_width = FALSE,
    position = "center"
  ) %>% 
row_spec(1, background = "#D3D3D3")%>%
  row_spec(0, bold = TRUE) %>% 
  column_spec(3, color = "red", bold = TRUE)

```

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# Reshape data to long format for plotting
oil_data_long <- oil_data %>%
  select(date, log_price_WTI, log_price_Brent) %>%
  pivot_longer(cols = starts_with("log_price"), names_to = "Type", values_to = "Log_Price") %>%
  mutate(Type = recode(Type, log_price_WTI = "WTI", log_price_Brent = "Brent"))

# Create the ggplot object
p_oil_data_long <- ggplot(oil_data_long, aes(x = date, y = Log_Price, color = Type)) +
  geom_line() +
  scale_color_manual(values = c("WTI" = "#ffde57", "Brent" = "#4584b6")) +
  labs(title = "Log-Transformed WTI and Brent Crude Oil Prices (1995-2020)",
       x = "",
       y = "Log Price (Natural Log of USD per Barrel)",
       color = "Crude Oil Type") +
  theme_minimal()

# Make it interactive
interactive_plot_long <- ggplotly(p_oil_data_long)
htmltools::div(interactive_plot_long, style = "display: flex; justify-content: center;")
```


## Q4 
<div class="boxed">

<p>Explore and discuss whether the Brent and WTI Oil log price series are non-stationary\
- Use ACF’s and Unit-Root tests\
- Note: For the unit root test use an appropriate lag order.</p>
</div>


```{r message=FALSE, warning=FALSE, paged.print=FALSE}
library(forecast)
# Plot ACF for log-transformed WTI prices
plot_acf_wti <- ggAcf(oil_data$log_price_WTI, main = "ACF of Log-Transformed WTI Prices")
# Plot ACF for log-transformed Brent prices
plot_acf_brent <- ggAcf(oil_data$log_price_Brent, main = "ACF of Log-Transformed Brent Prices")

grid.arrange(plot_acf_wti, plot_acf_brent, ncol = 2)
```


```{r message=FALSE, warning=FALSE, paged.print=FALSE}
# oil_data_clean <- na.omit(oil_data[, c("log_price_WTI", "log_price_Brent")])
# adf_wti <- adf.test(oil_data_clean$log_price_WTI, alternative = "stationary")
# adf_brent <- adf.test(oil_data_clean$log_price_Brent, alternative = "stationary")
# while both functions serve the purpose of conducting the ADF test, adf.test() is suitable for quick checks with minimal configuration, whereas ur.df() is more appropriate for detailed and customizable time series analysis.

library(urca)
oil_data_clean <- oil_data[!is.na(oil_data$log_price_WTI), ]
adf_wti <- ur.df(oil_data_clean$log_price_WTI, type = "drift", selectlags = "AIC")
summary(adf_wti)
adf_brent <- ur.df(oil_data_clean$log_price_Brent, type = "drift", selectlags = "AIC")
summary(adf_brent)
```
**Selecting the Appropriate Lag Order:**

The **selectlags = "AIC"** parameter in the **ur.df** function automatically selects the optimal lag length based on the Akaike Information Criterion (AIC). This approach ensures that the model **accounts for the necessary lagged terms without overfitting.**

**Interpreting ADF Test Results:**

<p>**Null Hypothesis (H₀):** The series has a **unit root (non-stationary)**.</p>
<p>**Alternative Hypothesis (H₁):** The series does not have a unit root (stationary).</p>

<p>If the test statistic is less than the critical value at a chosen significance level (e.g., 5%), we reject the null hypothesis, indicating that the series is stationary. Conversely, if we fail to reject the null hypothesis, it suggests that the series is non-stationary.</p>

**Conclusion:**
<p>Based on the ACF analysis and the results of the ADF tests, we can determine the stationarity of the log-transformed WTI and Brent crude oil price series. If both analyses indicate non-stationarity, it may be necessary to difference the series or apply other transformations to achieve stationarity before proceeding with further time series modeling.</p>

<br>

## Q5
<div class="boxed">

<p>Estimate and present results for a VAR(12) model\
• Any data that is non-stationary should be properly differenced to make it stationary first.\
• Make sure you interpret and discuss the results</p>
</div>
<br>
**Differencing the Data**
<br>
<p>Differencing transforms the data to stationary by removing trends and seasonality.</p>

```{r message=FALSE, warning=FALSE, paged.print=FALSE}
oil_data_diff <- oil_data %>%
  mutate(
    diff_log_price_WTI = c(NA, diff(log_price_WTI)),
    diff_log_price_Brent = c(NA, diff(log_price_Brent))
  )

oil_data_diff <- oil_data_diff %>%
  filter(!is.na(diff_log_price_WTI) & !is.na(diff_log_price_Brent))

```
<br>
<p>Selecting the Optimal Lag Length.\
Before fitting the VAR model, determine the appropriate lag length using information criteria.</p>
<br>
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
lag_selection <- VARselect(oil_data_diff[, c("diff_log_price_WTI", "diff_log_price_Brent")], lag.max = 12, type = "const")
print(lag_selection$selection)
```
<br>
<p>**Estimating the VAR(12) Model and Fit the VAR model with 12 lags.**</p>
<br>
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
var_model <- vars::VAR(oil_data_diff[, c("diff_log_price_WTI", "diff_log_price_Brent")], p = 12, type = "const")
summary(var_model)
```

<br>


## Q6
<br>
<div class="boxed">

<p>Are the log prices of WTI and Brent cointegrated?\
• Conduct a formal test of cointegration and interpret the result</p>
</div>

<br>
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
oil_data <- na.omit(oil_data)
# log transformation
oil_data <- oil_data %>%
  mutate(log_price_WTI = log(price_WTI),
         log_price_Brent = log(price_Brent))
# ADF test on log-transformed WTI prices
adf_wti <- ur.df(oil_data$log_price_WTI, type = "drift", selectlags = "AIC")
summary(adf_wti)

# ADF test on log-transformed Brent prices
adf_brent <- ur.df(oil_data$log_price_Brent, type = "drift", selectlags = "AIC")
summary(adf_brent)

# Step 1: OLS regression of log_price_WTI on log_price_Brent
ols_model <- lm(log_price_WTI ~ log_price_Brent, data = oil_data)
summary(ols_model)
# Extract residuals
residuals_ols <- resid(ols_model)
# Step 2: ADF test on residuals
adf_residuals <- ur.df(residuals_ols, type = "none", selectlags = "AIC")
summary(adf_residuals)

```
<br>
**Summary of Findings:**
<br>
<p>The analysis investigates the long-term relationship between the log-transformed prices of West Texas Intermediate (WTI) and Brent crude oil from January 1, 1995, to December 31, 2020.</p>

**1. Ordinary Least Squares (OLS) Regression:**

<p>An OLS regression was performed with `log_price_WTI` as the dependent variable and `log_price_Brent` as the independent variable.</p>

- **Regression Equation:** log_price_WTI = 0.374259 + 0.900938 * log_price_Brent

- **Key Statistics:**
  - **Intercept:** 0.374259 (p < 0.001)
  - **Slope Coefficient:** 0.900938 (p < 0.001)
  - **R-squared:** 0.989
  - **F-statistic:** 583,500 (p < 0.001)

**Interpretation:**

<p>The high **R-squared value (0.989)** indicates that approximately 98.9% of the variance in WTI log prices is explained by Brent log prices. The **slope coefficient of 0.900938** suggests a **strong positive relationship** between the two price series.</p>

**2. Augmented Dickey-Fuller (ADF) Test on Residuals:**

To assess cointegration, an ADF test was conducted on the residuals of the OLS regression.

- **Test Statistic:** -11.5398
- **Critical Values:**
  - 1%: -2.58
  - 5%: -1.95
  - 10%: -1.62

**Interpretation:**

<p>The test statistic (-11.5398) is significantly lower than the 1% critical value (-2.58), leading to the rejection of the null hypothesis of a unit root in the residuals. This indicates that the residuals are stationary, confirming that the log-transformed prices of WTI and Brent crude oil are cointegrated.</p>

**Conclusion:**

<p>The log-transformed prices of WTI and Brent crude oil exhibit a strong long-term equilibrium relationship, as evidenced by the high R-squared value in the OLS regression and the stationarity of the residuals. This cointegration implies that, despite short-term deviations, the two price series move together over time, maintaining a **stable long-term relationship.**</p>






## Q7

<div class="boxed">

<p>Estimate and present results for an appropriate VECM(12) model on log prices.\
• Is there a long-run relationship between WTI and Brent?\
• Interpret the speed of adjustment coefficients</p>
</div>


```{r message=FALSE, warning=FALSE, paged.print=FALSE}
library(tsDyn)
# Combine the log price series into a matrix
log_prices <- cbind(oil_data$log_price_WTI, oil_data$log_price_Brent)
colnames(log_prices) <- c("log_price_WTI", "log_price_Brent")

# Determine the number of cointegrating relationships
johansen_test <- ca.jo(log_prices, type = "trace", ecdet = "const", K = 13)
summary(johansen_test)

# Extract the cointegrating vector
cointegration_vector <- cajorls(johansen_test, r = 1)$beta
print(cointegration_vector)

# Fit the VECM with 12 lags
vecm_model <- VECM(log_prices, lag = 12, r = 1, include = "const", estim = "ML")
summary(vecm_model)
```


**Conclusion:**

<p>The analysis indicates a significant long-term relationship between West Texas Intermediate (WTI) and Brent crude oil prices. The high correlation and cointegration between these benchmarks suggest that global oil market events, including those outside North America, influence WTI prices over the long run.</p>

**Implications for the Firm:**

<p>Given the interconnectedness of WTI and Brent prices, the firm can consider the following strategies to manage risk and enhance profitability:</p>

1. **Hedging with Brent Contracts:**

   - <p>**Risk Mitigation:** Utilize Brent futures or options to hedge against price volatility, especially when global events are expected to impact oil markets.</p>
   
   - <p>**Diversification:** Incorporate Brent-based instruments to diversify the firm's hedging portfolio, reducing reliance solely on WTI-based contracts.</p>

2. **Spread Trading:**
   - <p>**Exploiting Price Differentials:** Engage in spread trading by taking positions on the price difference between WTI and Brent. This strategy can capitalize on temporary deviations from the long-term equilibrium relationship.</p>
   
   - <p>**Arbitrage Opportunities:** Monitor and act on arbitrage opportunities arising from discrepancies between WTI and Brent prices, adjusting positions as the spread converges.</p>

3. **Global Market Monitoring:**
   - <p>**Informed Decision-Making:** Stay vigilant to international events, such as geopolitical tensions or OPEC decisions, that may affect Brent prices and, consequently, WTI prices.</p>
   
   - <p>**Proactive Positioning:** Adjust trading strategies proactively in anticipation of global market shifts, leveraging insights into the Brent-WTI relationship.</p>

<p>By acknowledging the global factors influencing WTI prices and implementing these strategies, the firm can better manage its oil price risk and identify opportunities for profit in the interconnected oil markets.</p>

<br>

<span>  <span style="color: Steelblue;">**Md Mahmudul Hasan**</span> \
MQIM 3760573\
Faculty of Management \
University of New Brunswick \
mahmudul.hasan\@unb.ca \

<br>
