-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.Rhistory
More file actions
135 lines (135 loc) · 4.49 KB
/
Copy path.Rhistory
File metadata and controls
135 lines (135 loc) · 4.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
##### Setup the environment #####
# Install the required packages (uncomment to install all of them)
#install.packages(c("readr", "RTransferEntropy", "zoo", "e1071", "xts", "doParallel", "foreach", "tidyverse"))
# Load the required packages
library(readr)
library(RTransferEntropy)
library(zoo)
library(e1071)
library(xts)
library(doParallel)
library(foreach)
library(tidyverse)
# Load the data
Adj_Closing_prices <- read_csv("./full_df.csv")
Adj_Closing_prices$Date <- as.Date(Adj_Closing_prices$Date)
##### Point Estimate TE #####
# Get all columns to compare against BTC
all_cols <- colnames(Adj_Closing_prices)
other_cols <- setdiff(all_cols , c("Date", "BTC"))
# Register parallel backend
num_cores <- detectCores() - 1 # Detect number of CPU cores available on the machine and leave one core free for system processes to run
cl <- makeCluster(num_cores) # Get number of cores to be used for parallelization
registerDoParallel(cl) # Initialize the parallel backed for the 'foreach' functions to use the created cluster
# Run parallel foreach loop
results <- foreach(col = other_cols, .combine = rbind, .packages = c("RTransferEntropy", "zoo", "e1071", "xts", "tidyverse")) %dopar% {
cat("Processing", col, "...\n")
temp_df <- Adj_Closing_prices[, c("BTC", col)]
temp_df <- na.omit(temp_df)
if (nrow(temp_df) < 20) {
cat("Skipping", col, "- not enough data after removing NAs.\n")
return(NULL)
}
btc_ret <- diff(log(temp_df$BTC))
stock_ret <- diff(log(temp_df[[col]]))
returns_df <- na.omit(data.frame(btc_ret, stock_ret))
a <- returns_df$btc_ret
b <- returns_df$stock_ret
te <- tryCatch({
transfer_entropy(a, b,
nboot = 1000,
shuffles = 1000,
burn = 0,
seed = 42)
}, error = function(e) {
cat("Failed on", col, ":", e$message, "\n")
return(NULL)
})
if (!is.null(te)) {
coef <- te[3]$coef
data.frame(
Ticker = col,
MI_BTC_to_Ticker = coef[1],
MI_Ticker_to_BTC = coef[[2]],
p_BTC_to_Ticker = coef[7],
p_Ticker_to_BTC = coef[8],
stringsAsFactors = FALSE
)
} else {
NULL
}
}
# Stop cluster
stopCluster(cl)
# View or save results
print(results)
write.csv(results, "20_05_2025_PointEstimate_TransferEntropy_MSTR.csv")
##### Rolling TE #####
# Read the CSV
df <- read.csv("MSTR_BTC.csv", stringsAsFactors = FALSE)
dates <- as.Date(df$Date)
# Ensure numeric and select relevant columns
data <- df %>%
select(BTC, MSTR) %>%
mutate(across(everything(), as.numeric))
rownames(data) <- dates
# Convert to log returns
ret <- diff(log(as.matrix(data)))
ret <- na.omit(ret)
print(ret)
# Convert the data into an xts object
xts_data <- xts(ret, order.by = as.Date(df$Date[-1]))
# Create the list where the first element contains the xts object
data_list <- list(xts_data)
# Rolling Transfer Entropy
window_size <- 252 # ~1 year
step_size <- 1
n_steps <- floor((nrow(data_list[[1]]) - window_size) / step_size)
#time_index <- as.Date(rep(NA, n_steps))
# Prepare output
results_list <- list()
# Set up parallel backend
n_cores <- parallel::detectCores() - 2
cl <- makeCluster(n_cores)
registerDoParallel(cl)
for (ticker_index in 1:length(data_list)) {
stripped_names <- gsub("\\.Adjusted$", "", colnames(data_list[[ticker_index]])[[2]])
print(paste("Processing", stripped_names))
results <- foreach(i = seq(1, nrow(data_list[[ticker_index]]) - window_size+1, by = step_size),
.combine = rbind,
.packages = c("RTransferEntropy", "xts")) %dopar% {
window_x <- data_list[[ticker_index]][,1][i:(i+window_size-1)]
window_y <- data_list[[ticker_index]][,2][i:(i+window_size-1)]
cat("Step", i, ": BTC head =", head(window_x), "MSTR head =", head(window_y), "\n",
file = "te_debug_log.txt", append = TRUE)
if (any(is.na(window_x) | is.na(window_y))) return(rep(NA, 5))
te_xy_result <- suppressMessages(
suppressWarnings(
transfer_entropy(window_x, window_y, lx=1, ly=1,
burn = 0, nboot = 1000,
seed = 42, shuffles = 1000,
na.rm = TRUE)
)
)
as.numeric(c(index(data_list[[ticker_index]])[i + window_size -1],
te_xy_result$coef[1], te_xy_result$coef[7],
te_xy_result$coef[[2]], te_xy_result$coef[8]))
#te_crypto_stock[i] <- te_btc_stock
#te_stock_crypto[i] <- te_stock_btc
#pval_crypto_stock[i] <- p_btc_stock
#pval_stock_crypto[i] <- p_stock_btc
#}
#result_dates <- dates[rolling_indexes[, window_size]]
}
# Convert results to data.frame
df <- as.data.frame(results)
colnames(df) <- c("Date",
paste0("TE BTC-->", stripped_names),
paste0("p_values BTC-->", stripped_names),
paste0("TE ", stripped_names, "-->BTC"),
paste0("p_values ", stripped_names, "-->BTC"))
df$Date <- as.Date(df$Date)
results_list[[stripped_names]] <- df
}
stopCluster(cl)
write.csv(results_list$MSTR, "20_05_2025_Rolling_TransferEntropy_MSTR.csv")