Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Created August 28, 2024 20:30
Show Gist options
  • Save quantra-go-algo/70dd1442492240f70eef03b574e342c0 to your computer and use it in GitHub Desktop.
Save quantra-go-algo/70dd1442492240f70eef03b574e342c0 to your computer and use it in GitHub Desktop.
print(paste0(strrep('=',50)))
print(paste0(strrep('=',50)))
print(paste0(strrep('=',50)))
print(paste0('Estimation of TVP-VAR-SV 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 <- as.matrix(subset(var_data, date<iter_date)[,match(tickers,colnames(var_data))])
bv <- bvar.sv.tvp(data, nf=1, tau=40, nrep = 300, nburn=20)
forecast_ys <- rowMeans(bv$fc.ydraws[1:7,1,])
print(paste0('forecast_ys'))
print(paste0(forecast_ys))
# We go long if the forecast return is positive, otherwise, we make no position.
for (c in 1:length(tickers)) {
df_forecasts[i,paste0(tickers[c],'_tvp_var_signal')] = if (forecast_ys[c]>0) 1 else next
}
# Set the trade_done value as 1 to record up to which day we have progressed
df_forecasts[i,'trade_done'] <- 1
# Print the signals
for (ticker in tickers) {
print(paste0(ticker," tvp-var-sv signal is ",df_forecasts[i,paste0(ticker,'_tvp_var_signal')]))
}
# Save the df_forecasts dataframe
dataframe <- data.frame(coredata(df_forecasts))
write.xlsx(dataframe, 'df_results_tvp_var.xlsx')
}
} 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