It examines whether one event or variable directly influences another.
library(dplyr)
library(readxl)
library(tseries)
library(aTSA)
library(lmtest)
library(corrplot)We begin by importing the Excel files directly into the R console. This creates two data frames containing the historical closing prices of Apple and Walmart stocks. Next, we combine the relevant columns into a single data frame named df, separating the date and closing price values for both stocks. We then rename the columns for better readability.
AAPL = read_excel("AAPL.xlsx")
WMT = read_excel("WMT.xlsx")
df = data.frame(AAPL$Date, AAPL$Close, WMT$Close)
df
summary(df)
colnames(df) = c("DATE","AAPL","WMT")
To compute the correlation between the two stocks, we remove the date column because correlation analysis requires numerical variables only. This refined dataset (df_RD) is then used to calculate the correlation matrix.
df_RD = df[,-1 ] # Except Date
df_RD
cormatrix = cor(df_RD)
cormatrix
# PLOT
corrplot(cormatrix, method = "shade", tl.col = "black", addCoef.col = "black", cl.pos = "n", order = "AOE")
Stationarity is a fundamental requirement in time series analysis, as many statistical models rely on stable means and variances over time. To verify whether a series is stationary, we use the Augmented Dickey-Fuller (ADF) test, one of the most widely applied methods in econometrics. The accompanying plot provides a clear visual representation of the series’ behaviour, making it easier to interpret the stationarity
par(mfrow = c(1,2))
plot(df$AAPL, type = 'l', main = "APPLE")
plot(df$WMT, type = 'l', main = "WAL_MART")
adf.test(df$AAPL)
adf.test(df$WMT)
A = diff(df$AAPL)
str(A)
W = diff(df$WMT)
str(W)
par(mfrow = c(1,2))
plot(A, main = ("Diff of AAPL"), type = "l")
plot(W, main = ("Diff of WMT"), type = "l")
## Again to take the Agumented Dicky Fuller test.
adf.test(A)
adf.test(W)
After transforming the series to achieve stationarity, the data are now ready for Granger causality testing. This step allows us to determine whether past values of one stock can be used to predict the future values of the other, providing insights into the directional relationship between the two time series.
grangertest(A ~ W)
grangertest(W ~ A)
Post a Comment
The more questions you ask, the more comprehensive the answer becomes. What would you like to know?