# Time Series Classification Synthetic vs Real Financial Time Series – Part IX

Learn which R packages and data sets you need by reviewing Part IPart II ,Part III, Part IV, Part VPart VIPart VII and Part VIII of this series.

### How the training Y (predictor variable) data looks:

I set the data up for an XGBoost model:

I create a grid search in order search over a parameter space to locate the optimal parameters for the data set. It needs a little more work but it’s a pretty good starting point. I can just add code to the `expand.grid` function. That is, say I want to increase the depth of the tree I can add to `max_depth = c(5, 8, 14)` more parameters such as `max_depth = c(5, 8, 14, 1, 2, 3, 4, 6, 7)`. Note Adding parameters to the grid search increases computational time exponentially. Every parameter you add a value to, the model has to search all possible combinations associated with that parameter. That is, adding an `eta = c(0.1)` and `max_depth = c(5)` would give me the optimal parameter for one iteration/loop through the training model, i.e. an `eta = c(0.1)` mapped onto a `max_depth = c(5)`. Adding an additional value to the `eta = c(0.1, 0.3)` and `max_depth = c(5)` would map `eta = 0.1` onto `max_depth = 5` and `eta = 0.3` onto `max_depth = 5`. If I add another value such that `eta = c(0.1, 0.3, 0.4)` then all 3 of these values will be mapped to `max_depth = c(5)`. Adding values to the `max_depth = c(5)` parameter would add an extra layer of complexity to the grid search. This added into the fact that there are many parameters to optimize in an XGBoost model can drastically increase computational complexity. Thus, understanding the statistics behind the models in Machine Learning is important when trying to avoid getting stuck in a local minimum (which any greedy algorithm using gradient descent optimisation can do: greedy algorithm).

``````######################################################################
################# XGBoost Grid Search to locate Optimal Parameters ###

##############################################################################################################################
# NOTE: This section was taken from the first chapter of my PhD where I needed to search over a parameter space to locate the
# most optimal parameters - I have just adapted it for this problem of Time Series Classification.
# Its simple enough to add parameters and different values - I just optimise a few important parameters from domain knowledge
# of the XGBoost model for this task, i.e depth and eta are quite important in gradient boosting.

# 1) I create a "grid" with different parameter values or combinations of parameter values
# 2) I apply cross validation over the parameter space to fine the most optimal values for the XGBoost model.
# 3) I print the model parameters which give the best train / (in-sample test) results in a data table.
##############################################################################################################################

# Grid Search Parameters:
# 1)
searchGridSubCol <- expand.grid(subsample = c(1), #Range (0,1], default = 1, set to 0.5 will prevent overfitting
colsample_bytree = c(1), #Range (0,1], default = 1
max_depth = c(5, 8, 14), #Range (0, inf], default = 6
min_child = c(1), #Range (0, inf], default = 1
eta = c(0.1, 0.05, 0.3), #Range (0,1], default = 0.3
gamma = c(0), #Range (0, inf], default = 0
lambda = c(1), #Default = 1, L2 regularisation on weights, higher the more conservative the model
alpha = c(0), #Default = 0, L1 regularisation on weights, higher the more conservative the model
max_delta_step = c(0), #Range (0, inf], default = 0 (Helpful for logisitc regression when class is extremely imbalanced, set to value 1-10 may help control the update)
colsample_bylevel = c(1) #Range (0,1], default = 1
)

ntrees = 200
nfold <- 10                             # I use nfold = 10 which is probably too many folds, 5 should be sufficient.
watchlist <- list(train = dtrain, test = dval)

# 2)
system.time(
AUCHyperparameters <- apply(searchGridSubCol, 1, function(parameterList){
#Extract Parameters to test
currentSubsampleRate <- parameterList[["sub_sample"]]
currentColsampleRate <- parameterList[["colsample_bytree"]]
currentDepth <- parameterList[["max_depth"]]
currentEta <- parameterList[["eta"]]
currentMinChild <- parameterList[["min_child"]]
gamma <- parameterList[["gamma"]]
lambda <- parameterList[["lambda"]]
alpha <- parameterList[["alpha"]]
max_delta_step <- parameterList[["max_delta_step"]]
colsample_bylevel <- parameterList[["colsample_bylevel"]]
xgboostModelCV <- xgb.cv(data =  dtrain,
nrounds = ntrees,
nfold = nfold,
showsd = TRUE,
metrics = c("auc", "logloss", "error"),
verbose = TRUE,
"eval_metric" = c("auc", "logloss", "error"),
"objective" = "binary:logistic", #Outputs a probability "binary:logitraw" - outputs score before logistic transformation
"max.depth" = currentDepth,
"eta" = currentEta,
"gamma" = gamma,
"lambda" = lambda,
"alpha" = alpha,
"subsample" = currentSubsampleRate,
"colsample_bytree" = currentColsampleRate,
print_every_n = 50, # print ever 50 trees to reduce the outputs printed.
"min_child_weight" = currentMinChild,
booster = "gbtree", #booster = "dart"  #using dart can help improve accuracy.
early_stopping_rounds = 10,
watchlist = watchlist,
seed = 1234)
xvalidationScores <<- as.data.frame(xgboostModelCV\$evaluation_log)
train_auc_mean <- tail(xvalidationScores\$train_auc_mean, 1)
test_auc_mean <- tail(xvalidationScores\$test_auc_mean, 1)
train_logloss_mean <- tail(xvalidationScores\$train_logloss_mean, 1)
test_logloss_mean <- tail(xvalidationScores\$test_logloss_mean, 1)
train_error_mean <- tail(xvalidationScores\$train_error_mean, 1)
test_error_mean <- tail(xvalidationScores\$test_error_mean, 1)
output <- return(c(train_auc_mean, test_auc_mean, train_logloss_mean, test_logloss_mean, train_error_mean, test_error_mean, xvalidationScores, currentSubsampleRate, currentColsampleRate, currentDepth, currentEta, gamma, lambda, alpha, max_delta_step, colsample_bylevel, currentMinChild))
hypemeans <- which.max(AUCHyperparameters[[1]]\$test_auc_mean)
output2 <- return(hypemeans)
}))``````

The output of the grid search can be set into a nice data frame using the following code. However I did not save this output to file and therefore cannot read it in. You can view the output on the original Jupyter Notebook `In [49]` here

``````# 3)
output <- as.data.frame(t(sapply(AUCHyperparameters, '[', c(1:6, 20:29))))
varnames <- c("TrainAUC", "TestAUC", "TrainLogloss", "TestLogloss", "TrainError", "TestError", "SubSampRate", "ColSampRate", "Depth", "eta", "gamma", "lambda", "alpha", "max_delta_step", "col_sample_bylevel", "currentMinChild")
colnames(output) <- varnames
data.table(output)``````

According to the results at the time the optimal parameters were:

• ntrees = 95,
• eta = 0.1,
• max_depth = 5,

With the other parameters left to default settings for simplicity.

Visit Matthew Smith – R Blog to download the complete R code and see additional details featured in this tutorial: https://lf0.com/post/synth-real-time-series/financial-time-series/

##### Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Matthew Smith and is being posted with permission from Matthew Smith. The views expressed in this material are solely those of the author and/or Matthew Smith and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.