Close Navigation
Learn more about IBKR accounts
Time Series Classification Synthetic vs Real Financial Time Series – Part IX

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

Posted June 18, 2021
Matthew Smith
Matthew Smith - R Blog

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 X (input variables) data looks:

ac_9_ac_9acf_features_x_acf1acf_features_x_acf10acf_features_diff1_acf1acf_features_diff1_acf10acf_features_diff2_acf1acf_features_diff2_acf10ARCH.LMautocorr_features_embed2_incircle_1autocorr_features_embed2_incircle_2autocorr_features_ac_9autocorr_features_firstmin_acautocorr_features_trev_numautocorr_features_motiftwo_entro3autocorr_features_walker_propcrossbinarize_mean_binarize_meanbinarize_mean_NAcompengine_embed2_incircle_1compengine_embed2_incircle_2compengine_ac_9compengine_firstmin_accompengine_trev_numcompengine_motiftwo_entro3compengine_walker_propcrosscompengine_localsimple_mean1compengine_localsimple_lfitaccompengine_sampen_firstcompengine_std1st_dercompengine_spreadrandomlocal_meantaul_50compengine_spreadrandomlocal_meantaul_ac2compengine_histogram_mode_10compengine_outlierinclude_mdrmdcompengine_fluctanal_prop_r1crossing_pointsdist_features_histogram_mode_10dist_features_outlierinclude_mdrmdembed2_incircleentropyfirstmin_acfirstzero_acflat_spotsfluctanal_prop_r1_fluctanal_prop_r1arch_acfgarch_acfarch_r2garch_r2histogram_modealphabetahursthw_parameters_hw_parametershw_parameters_NAlocalsimple_taureslumpinessmax_kl_shifttime_kl_shiftmax_level_shifttime_level_shiftmax_var_shifttime_var_shiftmotiftwo_entro3nonlinearityoutlierinclude_mdrmdx_pacf5diff1x_pacf5diff2x_pacf5pred_features_localsimple_mean1pred_features_localsimple_lfitacpred_features_sampen_firstsampen_first_sampen_firstsampencscal_features_fluctanal_prop_r1spreadrandomlocal_meantaulstabilitystation_features_std1st_derstation_features_spreadrandomlocal_meantaul_50station_features_spreadrandomlocal_meantaul_ac2std1st_der_std1st_dernperiodsseasonal_periodtrendspikelinearitycurvaturee_acf1e_acf10trev_numtsfeatures_frequencytsfeatures_nperiodstsfeatures_seasonal_periodtsfeatures_trendtsfeatures_spiketsfeatures_linearitytsfeatures_curvaturetsfeatures_e_acf1tsfeatures_e_acf10tsfeatures_entropytsfeatures_x_acf1tsfeatures_x_acf10tsfeatures_diff1_acf1tsfeatures_diff1_acf10tsfeatures_diff2_acf1tsfeatures_diff2_acf10unitroot_kpssunitroot_ppwalker_propcross
68010.0498492-0.06420250.0542648-0.44234820.2575236-0.59813030.41495920.02714440.47104250.71814670.049849220.87545662.0573330.5598456010.47104250.71814670.049849220.87545662.0573330.5598456111.7045031.4604661.331.00-0.500.11153850.8604651139-0.500.11153850.47104250.98882082130.86046510.03322570.02444340.03704230.0287773-0.500.00010000.00010000.5000458NANA10.77696403.8272232091.0276711313.2545181952.0573330.06959180.11153850.04740590.56690701.0663179111.7045031.7045031.7045030.86046511.410.06396491.4604661.421.001.460466010.00694810.0000643-0.86289630.2636951-0.07190260.05877990.87545661010.00694810.0000643-0.86289630.2636951-0.07190260.05877990.9888208-0.06420250.0542648-0.44234820.2575236-0.59813030.41495920.1777957-246.96180.5598456
4209-0.0037257-0.01664000.0302609-0.54441820.3391695-0.70254010.58987600.03698550.39768340.6409266-0.003725710.07725892.0654800.5598456110.39768340.6409266-0.003725710.07725892.0654800.5598456111.7520281.4275911.391.00-0.25-0.10000000.4651163137-0.25-0.10000000.39768340.98664801140.46511630.03285640.02869410.03698550.0347972-0.250.00088430.00088430.5000458NANA10.22676053.5492292151.39031932.0177451432.0654800.0236440-0.10000000.00609880.48597301.0685267111.7520281.7520281.7520280.46511631.490.08319991.4275911.531.001.427591010.04316960.0000288-0.63563321.0362897-0.06081600.03589360.07725891010.04316960.0000288-0.63563321.0362897-0.06081600.03589360.9866480-0.01664000.0302609-0.54441820.3391695-0.70254010.58987600.0372919-268.47570.5598456
111680.0236704-0.02697490.0299079-0.49430060.2640054-0.66260270.49060380.12655690.44015440.66409270.02367042-0.45694012.0756660.4633205110.44015440.66409270.02367042-0.45694012.0756660.4633205111.7094661.4311441.521.000.25-0.09615380.16279071220.25-0.09615380.44015440.98829372140.16279070.14536740.14905400.12655690.12470210.250.04110750.00010000.5000458NANA10.38632912.8346912271.0962091232.7601581972.0756660.1218026-0.09615380.00885980.46436081.0505751111.7094661.7094661.7094660.16279071.610.06918481.4311441.501.001.431144010.01347810.0000342-0.6468298-1.1770328-0.04192910.0376999-0.45694011010.01347810.0000342-0.6468298-1.1770328-0.04192910.03769990.9882937-0.02697490.0299079-0.49430060.2640054-0.66260270.49060380.1743418-260.07580.4633205
5794-0.00070870.11948300.0616705-0.40628970.2206195-0.60167000.41379130.15565510.48062020.6782946-0.00070872-0.57974052.0666370.4787645100.48062020.6782946-0.00070872-0.57974052.0666370.4787645111.5583071.3285652.031.18-0.25-0.30000000.2325581120-0.25-0.30000000.48062020.98159632250.23255810.21986920.09410530.14062800.0756639-0.250.01258560.00010000.5477543NANA10.77727268.411092481.5736821463.8029861492.0666370.1381103-0.30000000.01930370.39595000.9255264111.5583071.5583071.5583070.23255811.980.13318271.3285652.011.271.328565010.01392330.0000358-0.89887480.93891280.10793460.0661260-0.57974051010.01392330.0000358-0.89887480.93891280.10793460.06612600.98159630.11948300.0616705-0.40628970.2206195-0.60167000.41379130.1182423-224.06700.4787645
8693-0.0814496-0.09844980.1142883-0.46880080.3181153-0.61661360.45558930.15087920.40540540.6602317-0.081449620.39883702.0605710.5250965010.40540540.6602317-0.081449620.39883702.0605710.5250965111.6512431.4842331.191.00-0.50-0.05769230.3488372136-0.50-0.05769230.40540540.97457642160.34883720.09460620.09376350.10571520.1052409-0.500.02695220.00010000.5000458NANA10.54957427.8537831951.0396411914.4587721872.0605710.1164590-0.05769230.04673390.58960741.1095330111.6512431.6512431.6512430.34883721.240.09982101.4842331.351.001.484233010.00332310.00005740.18874970.4564879-0.10229830.11715580.39883701010.00332310.00005740.18874970.4564879-0.10229830.11715580.9745764-0.09844980.1142883-0.46880080.3181153-0.61661360.45558930.0391658-262.90100.5250965
1073-0.12538730.15119120.0608605-0.38325230.2048003-0.58320670.38612830.08766920.40310080.6356589-0.125387320.24634312.0616980.4594595110.40310080.6356589-0.125387320.24634312.0616980.4594595111.7633811.3047922.441.13-0.250.12307690.1395349121-0.250.12307690.40310080.98679032240.13953490.07794680.06186250.06958780.0601294-0.250.07782940.00010000.5663347NANA10.31518847.5289041852.0692301772.3408041692.0616980.02795740.12307690.03105400.35277930.8978003111.7633811.7633811.7633810.13953492.450.08163221.3047922.351.231.304792010.02132440.0000306-0.55776930.61117260.13299040.07583450.24634311010.02132440.0000306-0.55776930.61117260.13299040.07583450.98679030.15119120.0608605-0.38325230.2048003-0.58320670.38612830.0849681-208.45460.4594595

How the training Y (predictor variable) data looks:

.
1
0
1
0
0
1

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 Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus 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 - R Blog and is being posted with its permission. The views expressed in this material are solely those of the author and/or Matthew Smith - R Blog and Interactive Brokers 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 buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. 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.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.