---
title: "Exploring the Dynamics Between Gold, Inflation, and Interest Rates in the U.S. Economy"
output:
  html_document: 
    code_download: true
    highlight: espresso
date: "`r Sys.Date()`"
---
#### **Md Mahmudul Hasan**
<!-- echo=FALSE: Hide code but display the output. -->
<!-- include=FALSE: Hide both code and output, useful for setup chunks. -->
<!-- message=FALSE and warning=FALSE: Suppress any messages or warnings. -->
<!-- fig.width and fig.height: Control the size of the plot. -->
<!-- out.width and out.height: Control the output size of the figure. -->
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.slim.min.js"></script>

<!-- Script to make all links open in a new tab -->
<script type="text/javascript">
  $(document).ready(function() {
  $('a').attr('target', '_blank');
  });
</script>
```{r message=FALSE, warning=FALSE, include=FALSE}
library(fpp2)
library(tidyquant)
library(tidyverse)
library(quantmod)
library(dplyr)
library(ggthemes)
library(curl)
library(readxl)
library(cowplot)
library(ggpubr)
library(plotly)
library(ggplot2)
library(reshape2)
library(gt)
library(gtExtras)
library(knitr)
```

# {.tabset}

## Assignment
**Assignment:** <p>Write a report suitable for sharing with your CIO on the relationship between Gold, Inflation, and Interest rates in the U.S. Use monthly data from January 01, 2005 - January 01, 2019 with the following variables:<p>
 1. <p>**Gold:** Monthly log returns generated from the close price of the ETF “SPDR Gold Shares”<p>
 2. <p>**Inflation:** Monthly rate of change of Consumer Price Index for All Urban Consumers: All Items in U.S. City Average\
  -   There is a seasonally adjusted and a non-seasonally adjusted version\
  -   Use the seasonally adjusted series\<p>
 3. <p>**Interest Rates:** Change in Market Yield on U.S. Treasury Securities at 2-Year Constant Maturity, Quoted on an Investment Basis<p>
<br>

**Include the following in your report alongside brief, relevant discussion:** <br>
 **1.** A full description of your final data sample (after any transformations). This includes # of observations, of missing values, mean, median, standard deviation, skewness, and kurtosis\ <br>
  -Discuss any important statistical properties and include a discussion of any evident departures from normality and any implications of those departures for an investor\ <br>
 **2.** Generate a time series plot of each variable of interest and describe any interesting patterns, trends, or “stories” behind the plot. (i.e. what was the narrative in the real world about the evolution of these variables over time?)\ <br>
  -Include proper plot labels, titles, captions, and sources\ <br>
 **3.** Run the following regressions, output regression tables, and discuss the relationships you find including a discussion of statistical significance:
  - Gold vs Inflation\ 
  - Gold vs Interest Rates\ 
  - Inflation vs Interest Rates\ 
  - Gold vs Interest Rates and Inflation\ <br>
 **4.** Discuss whether the regression of Gold on both interest rates and inflation (d) is a better model than the regression of gold on interest rates (b) and gold on inflation (a) individually.\ <br>
 **5.** Evaluate the Gold vs Interest Rate and Inflation regression (d) in part 3 for violations of the assumptions of OLS and identify any issues regarding:\ 
  - Heteroskedasticity\ 
  - Autocorrelation/Serial Correlation\ 
  - Normality of Residuals (Q-Q plot, Histogram, and a formal test)\ 
  - Include a discussion of how any issues may affect your results.\ <br>
 **6.** If there are problems identified in part 5 that should be addressed, re-run the regression of Gold on Interest Rates and Inflation with appropriate corrections.\ <br>
 **7.** One of the more difficult to evaluate assumptions of OLS is exogeneity. Do you think the regression of Gold on Inflation and Interest rates is likely to violate this assumption and why?\ <br>
 **8.** End with a brief (2-3 sentence) conclusion on the use of Gold as an inflation hedge in the current environment and any suggested next steps.\ <br>





## Gold Log Returns

**Gold: Monthly log returns generated from the close price of the ETF “SPDR Gold Shares” **

```{r message=FALSE, warning=FALSE}
df<-tidyquant::tq_get(x=c("GLD"), #GLD is the ticker 
                           get="stock.prices", #stock.prices >tq_get >Yahoo Finance
                           from ="2005-01-01",     
                           to= "2018-12-31") %>%  
  tq_transmute(select = close, mutate_fun = to.monthly,indexAt = "firstof") 
```

```{r message=FALSE, warning=FALSE}
# Note, the data we get daily, we have to transmute the data to monthly and first day of the month...
# "lastof" would take from the last day
df <- df %>%
  mutate(Gold_Log_Return = c(NA, diff(log(df$close))))


df %>% 
  ggplot(aes(date, Gold_Log_Return)) +
  geom_line(size = 1) +
  labs(title = "Close Price and Gold Log Return Over Time",
       x = "Date",
       y = "Gold_Log_Return") +
  theme(plot.title.position = 'plot', 
      plot.title = element_text(hjust = 0.5))+
  theme_minimal()

```

```{r echo=FALSE, message=FALSE, warning=FALSE}
head(df) %>%
  gt() %>% 
  gt_theme_guardian() %>% 
  tab_header(title = "Close Price and Gold Log Return Over Time")
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
df %>% 
  gt_plt_summary(title = "This is the summary of Gold Log Return Over Time")

```

## Inflation
<br>
**Consumer Price Index for All Urban Consumers(Seasonally Adjusted): All Items in U.S. City Average (CPIAUCSL)**\
```{r message=FALSE, warning=FALSE}
df_cpi<-tidyquant::tq_get(c("CPIAUCSL"), 
                           get="economic.data",
                           from="2005-01-01", 
                           to="2018-12-31")

df <- df %>%
  mutate(Inflation_Rate_of_Change = (df_cpi$price / lag(df_cpi$price, 1) - 1) * 100)
```

```{r echo=TRUE, message=FALSE, warning=FALSE}
head(df) %>%
  gt() %>% 
  gt_theme_guardian() %>% 
  tab_header(title = "Close Price, Gold Log Return and Inflation Rate of Change Over Time")
```

```{r echo=TRUE, message=FALSE, warning=FALSE}
df %>% 
  gt_plt_summary(title = "Summary of Gold Log Return and Inflation Rate of Change Over Time")
```

```{r eval=FALSE, message=FALSE, warning=FALSE, include=FALSE}
# Calculate the monthly rate of change using lag function
# df$Rate_of_Change <- (df$price / lag(df$price, 1) - 1) * 100
# Explanation:
# lag(CPI$price, 1): Shifts the price series by one time period to reference the previous month.
# CPI$price / lag(CPI$price, 1) - 1: This calculates the percentage change relative to the previous month.
# The * 100 converts the rate of change into a percentage.
# There’s no need to use diff() since we're comparing each month to the previous one.
# Now, the Rate_of_Change column should have the same length as your original data frame with the first value being NA due to the lagging process.
```

## Interest Rate
<br>
**Market Yield on U.S. Treasury Securities at 2-Year Constant Maturity, Quoted on an Investment Basis (DGS2)**\
```{r message=FALSE, warning=FALSE}

df_ir<-tidyquant::tq_get(c("DGS2"), 
                          get="economic.data", #economic.data indicates FRED
                          from="2005-01-01", 
                          to="2018-12-31") %>% 
  tidyr::pivot_wider(names_from = symbol, values_from = price) %>% 
  tq_transmute(mutate_fun = to.monthly, indexAt = "firstof")

df <- df %>%
  left_join(df_ir %>% 
              select(date, Interest_Rate_Change = DGS2), by = c("date" = "date"))

```

```{r echo=TRUE, message=FALSE, warning=FALSE}
head(df) %>%
  gt() %>% 
  gt_theme_guardian() %>% 
  tab_header(title = "Close Price, Gold Log Return, Inflation Rate and Interest Rate of Change Over Time")
```

```{r echo=TRUE, message=FALSE, warning=FALSE}
df %>% 
  gt_plt_summary(title = "This is the Summary")
```

## Calculations
<br>
**Relationship between Gold monthly log returns,VS Inflation (monthly rate of change) VS Interest rates (change in market yield)**

**we can use multiple regression analysis. In this analysis:**<br>
<p>The dependent variable could be Gold returns.
The independent variables would be Inflation (monthly rate of change) and Interest rates (change in market yield).\
<p>We can run a multiple linear regression to see how changes in Inflation and Interest rates affect the log returns of Gold.

```{r message=FALSE, warning=FALSE}
model <- lm(Gold_Log_Return ~ Inflation_Rate_of_Change + Interest_Rate_Change, data = df)
model_summary <- summary(model)
```

```{r message=FALSE, warning=FALSE}
# Residuals summary
residuals <- model_summary$residuals
residuals_summary <- c(min(residuals), quantile(residuals, c(0.25, 0.5, 0.75)), max(residuals))
```

```{r message=FALSE, warning=FALSE}
# Format the residuals in a data frame for better presentation
residuals_df <- data.frame(
  Statistic = c("Min", "1Q", "Median", "3Q", "Max"),
  Value = round(residuals_summary, 6)
)
```

```{r message=FALSE, warning=FALSE}
# Format the coefficients in a data frame for better presentation
coefficients_df <- data.frame(
  Variable = rownames(model_summary$coefficients),
  Estimate = round(model_summary$coefficients[, 1], 7),
  `Std. Error` = round(model_summary$coefficients[, 2], 7),
  `t-value` = round(model_summary$coefficients[, 3], 3),
  `p-value` = round(model_summary$coefficients[, 4], 3)
)
```


```{r message=FALSE, warning=FALSE}
# Extract model statistics
rse <- round(model_summary$sigma, 5)
r_squared <- round(model_summary$r.squared, 5)
adj_r_squared <- round(model_summary$adj.r.squared, 7)
f_statistic <- round(model_summary$fstatistic[1], 4)
f_pvalue <- round(pf(model_summary$fstatistic[1], 
                     model_summary$fstatistic[2], 
                     model_summary$fstatistic[3], 
                     lower.tail = FALSE), 4)
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
kable(residuals_df)
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
kable(coefficients_df)
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
cat(paste("Residual Standard Error:", rse, "(on", model_summary$df[2], "degrees of freedom)\n"))
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
cat(paste("Multiple R-squared:", r_squared, "\n"))
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
cat(paste("Adjusted R-squared:", adj_r_squared, "\n"))
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
cat(paste("F-statistic:", f_statistic, "(on", model_summary$fstatistic[2], "and", model_summary$fstatistic[3], "DF)  p-value:", f_pvalue, "\n"))
```



```{r}
library(stargazer)
# Regressions
reg_a <- lm(Gold_Log_Return ~ Inflation_Rate_of_Change, data = df)

reg_b <- lm(Gold_Log_Return ~ Interest_Rate_Change, data = df)

reg_c <- lm(Inflation_Rate_of_Change ~ Interest_Rate_Change, data = df)

reg_d <- lm(Gold_Log_Return ~ Interest_Rate_Change + Inflation_Rate_of_Change, data = df)

stargazer(reg_a, reg_b, reg_c, reg_d, 
          type = "text",        # 'text' for console, 'html' or 'latex' for documents
          title = "Regression Results: Gold, Inflation, and Interest Rates", 
          dep.var.labels = c("Gold Log Return", "Inflation Rate of Change"),
          covariate.labels = c("Inflation Rate of Change", "Interest Rate Change"),
          out = "regression_output.txt")  # save the output to a .txt file

```

Breusch-Pagan Test for Heteroskedasticity
```{r}
library(lmtest)
bptest(reg_d)
```

Interpretation:
If the p-value is less than 0.05, then you reject the null hypothesis of homoscedasticity, meaning there is evidence of heteroskedasticity.
Heteroskedasticity affects the standard errors, which means the significance of your coefficients might be misestimated.

Plotting Residuals vs. Fitted Values
```{r}
# Plot residuals vs fitted values
plot(reg_d$fitted.values, reg_d$residuals, 
     xlab = "Fitted Values", ylab = "Residuals", 
     main = "Residuals vs Fitted")
abline(h = 0, col = "red")

```
Interpretation:
If the spread of residuals increases or decreases as the fitted values increase, this indicates heteroskedasticity.


Autocorrelation/Serial Correlation:
```{r}
# Perform Durbin-Watson test for autocorrelation
dwtest(reg_d)

```
Interpretation:
The Durbin-Watson statistic ranges from 0 to 4.
A value near 2 indicates no autocorrelation.
A value closer to 0 indicates positive autocorrelation.
A value closer to 4 indicates negative autocorrelation.
If the p-value is less than 0.05, autocorrelation is present, which can bias the coefficient estimates and affect hypothesis testing.




Q-Q Plot for Normality of Residuals
```{r}
# Q-Q plot for normality
qqnorm(residuals(reg_d))
qqline(residuals(reg_d), col = "red")

```
Interpretation:
If the points follow the 45-degree line closely, then the residuals are normally distributed.
Deviations from the line suggest non-normality.





Histogram of Residuals
```{r}
# Histogram of residuals
hist(residuals(reg_d), main = "Histogram of Residuals", 
     xlab = "Residuals", col = "lightblue")

```
Interpretation:
A bell-shaped histogram suggests that the residuals are normally distributed.



Shapiro-Wilk Test for Normality
```{r}
# Perform Shapiro-Wilk test for normality
shapiro.test(residuals(reg_d))

```
Interpretation:
If the p-value is less than 0.05, the residuals are not normally distributed. Non-normality can affect the validity of confidence intervals and hypothesis tests.


Heteroskedasticity:
```{r}
library(sandwich)

# Re-run the regression with robust standard errors
coeftest(reg_d, vcov = vcovHC(reg_d, type = "HC1"))
```



<br>
**Model Summary**<br>
**Gold_Log_Return ∼ Inflation_Rate_of_Change + Interest_Rate_Change**<br>
<p>This indicates that we are trying to explain the log returns of gold using changes in inflation rates and changes in interest rates.<br>

**Residuals:**
<p> The residuals are the differences between the observed values and the predicted values from the model. The summary statistics indicate that the residuals are fairly symmetrically distributed, with minimum and maximum values showing some dispersion around zero.<br>
**Coefficients:**
**Intercept:** 
0.0003414
<p>This is the estimated value of Gold Log Returns when both Inflation Rate of Change and Interest Rate Change are zero.

<br>
**Inflation Rate of Change: **
0.0075258
<p>For each unit increase in the inflation rate change, the Gold Log Return is estimated to increase by approximately 0.0075, holding the interest rate change constant. However, the p-value (0.553) indicates that this coefficient is not statistically significant, suggesting a weak relationship.

<br>
**Interest Rate Change: **
0.0028289
<p>For each unit increase in the interest rate change, the Gold Log Return is estimated to increase by approximately 0.0028, holding the inflation rate change constant. The p-value (0.277) suggests this coefficient is also not statistically significant.


<br>
**Residual Standard Error:**
0.05104 indicates the average distance that the observed values fall from the regression line.


<br>
**R-squared:**\
Multiple R-squared: 
0.01127<br>
Adjusted R-squared: 
−0.0007894
<p>This suggests that only about 1.1% of the variability in Gold Log Returns is explained by the model. The adjusted R-squared being negative implies that the model is not better than a simple mean model, indicating poor explanatory power.<br>


**F-statistic and p-value:**

**F-statistic:** 0.9345 with **p-value:** 0.3949
The overall model is **not statistically significant**, suggesting that neither of the predictor variables 
(Inflation Rate of Change and Interest Rate Change) contribute meaningfully to explaining the variation in Gold Log Returns.
<br>


**Implications of the Model Weak Relationships: **
<p> The coefficients for both inflation and interest rate changes are **not statistically significant**, 
meaning there is no strong evidence to suggest that changes in inflation or interest rates 
have a meaningful impact on gold returns in this model.<br>

<p>**Low Predictive Power:** \
The low R2 (R-squared) values indicate that the model does not explain much of the variability in gold log returns, suggesting that other factors not included in the model may be influencing gold returns.<br>

<p>**Further Investigation:** Given these results, it may be worthwhile to explore additional variables,
consider nonlinear relationships, or examine interactions among variables to better understand what influences gold returns.<br>

<p>**Caution in Interpretation:** The non-significance of the predictors means caution should be taken when interpreting these relationships, as they may not hold true outside of this specific model.<br>

**In summary,** the regression results imply that the model does not significantly explain variations in gold log returns based on inflation and interest rate changes. Further analysis may be needed to identify other influencing factors.


<br>

<span>  <span style="color: Steelblue;">**Md Mahmudul Hasan**</span> \
MQIM 3760573\
Faculty of Management \
University of New Brunswick \
mahmudul.hasan\@unb.ca \

<br>