<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/forecasting-markets-using-extreme-gradient-boosting-xgboost/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.quantinsti.com/blog/forecasting-markets-using-extreme-gradient-boosting-xgboost/"> R programming</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 1882px) 100vw, 1882px" alt="Forecasting Markets using eXtreme Gradient Boosting (XGBoost) " class="wp-image-7892" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/Forecasting-Markets-using-Gradient-Boosting.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>By <a target="_blank" rel="nofollow" href="https://www.linkedin.com/in/milind-paradkar-b37292107/">Milind Paradkar</a></p>
<p>In recent years, machine learning has been generating a lot of curiosity for its profitable application to trading. Numerous machine learning models like Linear/Logistic regression, Support Vector Machines, Neural Networks, Tree-based models etc. are being tried and applied in an attempt to analyze and forecast the markets. Researchers have found that some models have more success rate compared to other machine learning models. eXtreme Gradient Boosting also called XGBoost is one such machine learning model that has received rave from the machine learning practitioners.</p>
<p>In this post, we will cover the basics of XGBoost, a winning model for many kaggle competitions. We then attempt to develop an XGBoost stock forecasting model using the “xgboost” package in R programming.</p>
<h3><strong>Basics of XGBoost and related concepts</strong></h3>
<p>Developed by Tianqi Chen, the eXtreme Gradient Boosting (XGBoost) model is an implementation of the gradient boosting framework. Gradient Boosting algorithm is a machine learning technique used for building predictive tree-based models. (<a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/understanding-decision-trees/">Machine Learning: An Introduction to Decision Trees</a>).</p>
<p>Boosting is an ensemble technique in which new models are added to correct the errors made by existing models. Models are added sequentially until no further improvements can be made.</p>
<p>The ensemble technique uses the tree ensemble model which is a set of classification and regression trees (CART). The ensemble approach is used because a single CART, usually, does not have a strong predictive power. By using a set of CART (i.e. a tree ensemble model) a sum of the predictions of multiple trees is considered.</p>
<p>Gradient boosting is an approach where new models are created that predict the residuals or errors of prior models and then added together to make the final prediction.</p>
<p>The objective of the XGBoost model is given as:</p>
<p><strong>Obj = L + </strong><strong>Ω</strong></p>
<p>Where,<br>
L is the loss function which controls the predictive power, and<br>
Ω is regularization component which controls simplicity and overfitting</p>
<p>The loss function (L) which needs to be optimized can be Root Mean Squared Error for regression, Logloss for binary classification, or mlogloss for multi-class classification.</p>
<p>The regularization component (Ω) is dependent on the number of leaves and the prediction score assigned to the leaves in the tree ensemble model.</p>
<p>It is called gradient boosting because it uses a <a target="_blank" rel="nofollow" href="http://www.onmyphd.com/?p=gradient.descent">gradient descent algorithm</a> to minimize the loss when adding new models. The Gradient boosting algorithm supports both regression and classification predictive modeling problems.</p>
<h3><strong>Sample XGBoost model:</strong></h3>
<p>We will use the “xgboost” R package to create a sample XGBoost model. You can refer to the documentation of the “xgboost” package <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/xgboost/xgboost.pdf">here</a>.</p>
<p><strong>Install and load the xgboost library –</strong></p>
<p>We install the xgboost library using the install.packages function. To load this package we use the library function. We also load other relevant packages required to run the code.</p>
<pre>install.packages(&quot;xgboost&quot;)

# Load the relevant libraries
library(quantmod); library(TTR); library(xgboost);</pre>
<p>
 </p>
<p><strong>Create the input features and target variable – </strong>We take the 5-year OHLC and volume data of a stock and compute the technical indicators (input features) using this dataset. The indicators computed include Relative Strength Index (RSI), Average Directional Index (ADX), and Parabolic SAR (SAR). We create a lag in the computed indicators to avoid the look-ahead bias. This gives us our input features for building the XGBoost model. Since this is a sample model, we have included only a few indicators to build our set of input features.</p>
<pre># Read the stock data 
symbol = &quot;ACC&quot;
fileName = paste(getwd(),&quot;/&quot;,symbol,&quot;.csv&quot;,sep=&quot;&quot;) ; 
df = as.data.frame(read.csv(fileName))
colnames(df) = c(&quot;Date&quot;,&quot;Time&quot;,&quot;Close&quot;,&quot;High&quot;, &quot;Low&quot;, &quot;Open&quot;,&quot;Volume&quot;)

# Define the technical indicators to build the model 
rsi = RSI(df$Close, n=14, maType=&quot;WMA&quot;)
adx = data.frame(ADX(df[,c(&quot;High&quot;,&quot;Low&quot;,&quot;Close&quot;)]))
sar = SAR(df[,c(&quot;High&quot;,&quot;Low&quot;)], accel = c(0.02, 0.2))
trend = df$Close - sar

# create a lag in the technical indicators to avoid look-ahead bias 
rsi = c(NA,head(rsi,-1)) 
adx$ADX = c(NA,head(adx$ADX,-1)) 
trend = c(NA,head(trend,-1))</pre>
<p>
Our objective is to predict the direction of the daily stock price change (Up/Down) using these input features. This makes it a binary classification problem. We compute the daily price change and assigned a positive 1 if the daily price change is positive. If the price change is negative, we assign a zero value.</p>
<pre># Create the target variable
price = df$Close-df$Open
class = ifelse(price &amp;gt; 0,1,0)</pre>
<p>
 </p>
<p><strong>Combine the input features into a matrix – </strong>The input features and the target variable created in the above step are combined to form a single matrix. We use the matrix structure in the XGBoost model since the xgboost library allows data in the matrix format.</p>
<pre># Create a Matrix
model_df = data.frame(class,rsi,adx$ADX,trend)
model = matrix(c(class,rsi,adx$ADX,trend), nrow=length(class))
model = na.omit(model)
colnames(model) = c(&quot;class&quot;,&quot;rsi&quot;,&quot;adx&quot;,&quot;trend&quot;)</pre>
<p>
 </p>
<p><strong>Split the dataset into training data and test data – </strong>In the next step, we split the dataset into training and test data. Using this training and test dataset we create the respective input features set and the target variable.</p>
<pre># Split data into train and test sets 
train_size = 2/3
breakpoint = nrow(model) * train_size

training_data = model[1:breakpoint,]
test_data = model[(breakpoint+1):nrow(model),]

# Split data training and test data into X and Y
X_train = training_data[,2:4] ; Y_train = training_data[,1]
class(X_train)[1]; class(Y_train)

X_test = test_data[,2:4] ; Y_test = test_data[,1]
class(X_test)[1]; class(Y_test)</pre>
<p>
 </p>
<p><strong>Train the XGBoost model on the training dataset –</strong></p>
<p>We use the xgboost function to train the model. The arguments of the xgboost function are shown in the picture below.</p>
<p><img sizes="(max-width: 635px) 100vw, 635px" alt="" class="wp-image-7867" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-6.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>The data argument in the xgboost function is for the input features dataset. It accepts a matrix, dgCMatrix, or local data file. The nrounds argument refers to the max number of iterations (i.e. the number of trees added to the model). The obj argument refers to the customized objective function. It returns gradient and second order gradient with given prediction and dtrain.</p>
<pre># Train the xgboost model using the &quot;xgboost&quot; function
dtrain = xgb.DMatrix(data = X_train, label = Y_train)
xgModel = xgboost(data = dtrain, nround = 5, objective = &quot;binary:logistic&quot;)</pre>
<p>
 </p>
<p><strong>Output – </strong>The output is the classification error on the training data set.</p>
<p><img sizes="(max-width: 702px) 100vw, 702px" alt="" class="wp-image-7871" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-8.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Cross-validation</strong></p>
<p>We can also use the cross-validation function of xgboost i.e. xgb.cv. In this case, the original sample is randomly partitioned into nfold equal size subsamples. Of the nfold subsamples, a single subsample is retained as the validation data for testing the model, and the remaining (nfold – 1) subsamples are used as training data. The cross-validation process is then repeated nrounds times, with each of the nfold subsamples used exactly once as the validation data.</p>
<pre># Using cross validation
dtrain = xgb.DMatrix(data = X_train, label = Y_train)
cv = xgb.cv(data = dtrain, nround = 10, nfold = 5, objective = &quot;binary:logistic&quot;)</pre>
<p>
 </p>
<p><strong>Output – </strong>The xgb.cv returns a data.table object containing the cross validation results.</p>
<p><img sizes="(max-width: 708px) 100vw, 708px" alt="" class="wp-image-7875" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-10.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Make predictions on the test data</strong></p>
<p>To make predictions on the unseen data set (i.e. the test data), we apply the trained XGBoost model on it which gives a series of numbers.</p>
<pre># Make the predictions on the test data
preds = predict(xgModel, X_test)

# Determine the size of the prediction vector
print(length(preds))

# Limit display of predictions to the first 6
print(head(preds))</pre>
<p>
 </p>
<p><strong>Output – </strong></p>
<p><img sizes="(max-width: 707px) 100vw, 707px" alt="" class="wp-image-7878" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-12.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>These numbers do not look like binary classification {0, 1}. We have to, therefore, perform a simple transformation before we are able to use these results. In the example code shown below, we are comparing the predicted number to the threshold of 0.5. The threshold value can be changed depending upon the objective of the modeler, the <a target="_blank" rel="nofollow" href="https://www.kaggle.com/wiki/Metrics/history/1372">metrics</a> (e.g. F1 score, Precision, Recall) that the modeler wants to track and optimize.</p>
<pre>prediction = as.numeric(preds &amp;gt; 0.5)
print(head(prediction))</pre>
<p>
 </p>
<p><strong>Output – </strong></p>
<p><img sizes="(max-width: 712px) 100vw, 712px" alt="" class="wp-image-7881" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-14.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Measuring model performance</strong></p>
<p>Different evaluation metrics can be used to measure the model performance. In our example, we will compute a simple metric, the average error. It compares the predicted score with the threshold of 0.50.</p>
<p>For example: If the predicted score is less than 0.50, then the (preds > 0.5) expression gives a value of 0. If this value is not equal to the actual result from the test data set, then it is taken as a wrong result.</p>
<p>We compare all the preds with the respective data points in the Y_test and compute the average error. The code for measuring the performance is given below. Alternatively, we can use hit rate or create a confusion matrix to measure the model performance.</p>
<pre># Measuring model performance
error_value = mean(as.numeric(preds &amp;gt; 0.5) != Y_test)
print(paste(&quot;test-error=&quot;, error_value))</pre>
<p>
 </p>
<p><strong>Output – </strong></p>
<p><img sizes="(max-width: 674px) 100vw, 674px" alt="" class="wp-image-7884" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-16.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Plot the feature importance set – </strong>We can find the top important features in the model by using the xgb.importance function.</p>
<pre># View feature importance from the learnt model
importance_matrix = xgb.importance(model = xgModel)
print(importance_matrix)</pre>
<p>
 </p>
<p><img sizes="(max-width: 675px) 100vw, 675px" alt="" class="wp-image-7886" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-18.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Plot the XGBoost Trees</strong></p>
<p>Finally, we can plot the XGBoost trees using the xgb.plot.tree function. To limit the plot to a specific number of trees, we can use the n_first_tree argument. If NULL, all trees of the model are plotted.</p>
<pre># View the trees from a model
xgb.plot.tree(model = xgModel)

# View only the first tree in the XGBoost model
xgb.plot.tree(model = xgModel, n_first_tree = 1)</pre>
<p>
 </p>
<p><img sizes="(max-width: 651px) 100vw, 651px" alt="" class="wp-image-7889" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/XGB-20.png?w=450&ssl=1" data-recalc-dims="1"></p>
<h3><strong>Conclusion</strong></h3>
<p>This post covered the popular XGBoost model along with a sample code in R programming to forecast the daily direction of the stock price change. Readers can catch some of our previous machine learning blogs (links given below). We will be covering more machine learning concepts and techniques in our coming posts.</p>
<p><a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/predictive-modeling-algorithmic-trading/">Predictive Modeling in R for Algorithmic Trading</a><br>
<a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/machine-learning-application-forex-markets-working-models/">Machine Learning and Its Application in Forex Markets</a></p>
<h3><strong>Next Step</strong></h3>
<p>If you want to learn various aspects of <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/">Algorithmic trading</a> then check out the <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Executive Programme in Algorithmic Trading (EPAT™)</a>. The course covers training modules like Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading. EPAT™ equips you with the required skill sets to be a successful trader. <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Enroll now</a>!</p>
<p>The post <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/forecasting-markets-using-extreme-gradient-boosting-xgboost/">Forecasting Markets using eXtreme Gradient Boosting (XGBoost)</a> appeared first on <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/"></a>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.quantinsti.com/blog/forecasting-markets-using-extreme-gradient-boosting-xgboost/"> R programming</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/IEmbDLG2Ad4"></a></div>