Created
August 28, 2024 20:26
-
-
Save quantra-go-algo/cadd197938d592b5430591cc03142327 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print(paste0(strrep('=',50))) | |
print(paste0(strrep('=',50))) | |
print(paste0(strrep('=',50))) | |
print(paste0('Estimation of basic-VAR forecasts')) | |
# Check if VAR forecasts have already been estimated | |
if (length(as.numeric(rownames(tail(subset(df_forecasts, trade_done == 1) ,1))))==0) { | |
print(paste0(strrep('=',50))) | |
print(paste0(strrep('=',50))) | |
print(paste0(strrep('=',50))) | |
print(paste0('Estimation of VAR forecasts')) | |
if (length(initial_iloc_to_forecast<nrow(df_forecasts))!=0) { | |
# The for loop to estimate the model each day | |
for (i in initial_iloc_to_forecast:nrow(df_forecasts)) { | |
# Set the current iteration date | |
iter_date <- df_forecasts[i,'date'] | |
# Print the date | |
print(paste0(strrep('=',50))) | |
print(paste0("Date is ",iter_date)) | |
# Select the the 6 years of data to train the model | |
data <- subset(var_data, var_data$date<iter_date)[,match(tickers,colnames(var_data))] | |
# Estimate up to the 15-lag VAR with no constants or trends | |
lagselect <- VARselect(data, lag.max = 15, type = "none") | |
# Choose the best lag order as per the Bayesian Information Criteria | |
lag_order <- lagselect$selection[3] | |
# Estimate the best VAR model | |
model <- VAR(data, p = lag_order, type = "none", season = NULL, exog = NULL) | |
# Forecast one step ahead | |
var_forecast <- predict(model, n.ahead = 1) | |
# We go long if the forecast return is positive, otherwise, we make no position. | |
for (ticker in tickers) { | |
df_forecasts[i,paste0(ticker,'_var_signal')] = if (var_forecast$fcst[[ticker]][1]>=0) 1 else next | |
} | |
# Print the signals | |
for (ticker in tickers) { | |
print(paste0(ticker," var signal is ",df_forecasts[i,paste0(ticker,'_var_signal')])) | |
} | |
} | |
} else { | |
print(paste0('Estimation of TVP-VAR-SV forecasts has been completed before...')) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment