Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Last active September 21, 2023 15:45
# Set the number of cores to be used for parallelize the ARFIMA estimation
nCores <- detectCores() - 1
# A function to estimate the ARFIMA model
arfima_func <- function(data) {
# Estimate the ARFIMA model
arfima_fit <- autoarfima(data, ar.max = 5, ma.max = 5, criterion = "BIC", method = "partial",
arfima = TRUE, include.mean = TRUE, cluster = cluster,
distribution.model = "norm", solver = "hybrid", return.all = FALSE)
return(arfima_fit)
}
# A function to stop runningn the ARFIMA model in case it takes more 10 minutes to run
myWrapperFunction <- function(data) {
result = tryCatch(expr = withTimeout(arfima_func(data), timeout = 10*60),
TimeoutException = function(ex) "TimedOut")
return(result)
}
# The for loop to estimate the ARFIMA model each day
for (i in (initial_iloc_to_forecast):nrow(data)) {
start_time <- Sys.time()
# Select the corresponding 6-year previous data to train the ARFIMA model
#data_sample <- subset(data, !(data$date %in% dates_to_be_removed))
data_sample <- data$AAPL[((i-1)-(span-1)):(i-1)]
# Print some days info
print(paste0(strrep('=',50)))
print(paste0("Forecast ",(i+1-initial_iloc_to_forecast), ' out of ', length(df_forecasts$date)))
# Make the cluster based on the previous number of cores
cluster <- makePSOCKcluster(nCores)
# Estimate the ARFIMA model for this day
arfima_fit <- myWrapperFunction(data_sample)
# Stop the CPU multithreading
stopCluster(cluster)
if (typeof(arfima_fit)!="list") {
# Print a statement saying estimtation took too long
print(paste0("Estimation took longer than expected. Today's signal will be 0."))
# Signal will be 0 this day
df_forecasts[(i+1-initial_iloc_to_forecast),'signal'] <- 0.0
# Save the df_forecasts in an excel file
write.xlsx(df_forecasts, 'df_forecasts_in_R_v01.xlsx')
# Print some important things for log
print(paste0("Date is ",df_forecasts[(i+1-initial_iloc_to_forecast),]$date))
print(paste0("Signal is ",df_forecasts[(i+1-initial_iloc_to_forecast),'signal']))
print(paste0("Start time is ",start_time))
end_time <- Sys.time()
print(paste0("End time is ",end_time))
#calculate time difference in minutes
diff <- difftime(end_time, start_time, units="mins")
print(paste0("Time passed is ",round(diff,2)," minutes"))
} else {
# Obtain the data sample Apple last price
last_apple_price <- tail(data_sample,1)[[1]]
# Forecast the next day Apple stock close price forecast
forecast <- arfimaforecast(arfima_fit$fit, data=data_sample, n.ahead=1)@forecast$seriesFor[1]
# Go long if the forecast is higher than the previous-day stock close price
df_forecasts[(i+1-initial_iloc_to_forecast),'signal'] <- if (forecast>=last_apple_price) 1 else 0
# Save the df_forecasts in an excel file
write.xlsx(df_forecasts, 'df_forecasts_in_R_v01.xlsx')
print(paste0("Date is ",df_forecasts[(i+1-initial_iloc_to_forecast),]$date))
print(paste0('Price forecast is ',forecast))
print(paste0('Last AAPL price is ',last_apple_price))
print(paste0("Signal is ",df_forecasts[(i+1-initial_iloc_to_forecast),'signal']))
print(paste0("Start time is ",start_time))
end_time <- Sys.time()
print(paste0("End time is ",end_time))
#calculate time difference in minutes
diff <- difftime(end_time, start_time, units="mins")
print(paste0("Time passed is ",round(diff,2)," minutes"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment