Understanding and Visualizing Stock Market Absorption Ratio over Time Using R Code
Here is the complete code that uses your data to calculate and plot the absorption ratio over time:
# Load necessary libraries
library(ggplot2)
# Create data in the right shape
data <- read.csv("your_data.csv")
Ret <- data[,-1]
# lookback period in number of days (rolling window)
lb.period <- 500
nRow <- nrow(Ret)
nCol <- ncol(Ret)
n <- nRow-lb.period
ar <- rep(0,n) # reserve space for daily absorption ratio
for(i in 1:n) {
start <- i
end <- i+lb.period-1
ret <- Ret[start:end,]
cov <- cov(ret)
eigenval <- eigen(cov)$values
sumeigenval <- sum(eigenval)
abs <- eigenval[1:2]/sumeigenval # variance explained by 2 eigenvectors
ar[i] <- ar[i]+abs # daily absorption ratio, out of sample period
}
ar_new <- c(rep(NA, lb.period), ar) # add NaN values at the start
# bring data together with new absorption ratio
results <- bind_cols(data, Absorption = ar_new)
# plot results
results %>%
ggplot(
aes(
x = NoDur,
y = Absorption
)
) +
geom_line() +
theme_minimal() +
labs(
x = "",
y = "",
title = "Absorption Ratio over Time"
)
# save the plot to a file
ggsave("absorption_ratio.png", width=10, height=6)
Note that you will need to replace "your_data.csv"
with the actual path and name of your data file. Also, make sure that the data is in a format that can be read by read.csv()
function.
Please note that this code assumes that the data is in a comma-separated values (CSV) format. If it’s in a different format, you may need to adjust the code accordingly.
Last modified on 2024-08-08