XGBoost stock market prediction works by training an ensemble of gradient-boosted decision trees on features such as moving averages, RSI and ATR to forecast the next day’s close or direction. The original model below reports an R-squared of 0.9996 on Nifty, but when I re-ran it in 2026 with a proper time-ordered test, it did no better than simply assuming tomorrow’s close equals today’s. This post keeps the original code and adds the corrected version, so you can see both and avoid the same trap.
Forecasting the trajectory of the stock market remains an elusive endeavor for both investors and traders alike. A myriad of methods and algorithms have emerged over time, striving to address this complex issue, and have achieved varying levels of success. In this blog post, we will discuss the XGBoost algorithm and how it performs better than linear regression for predicting market direction. We will also provide a Python code example for predicting the next day’s NIFTY close and direction using XGBoost.

- XGBoost can model non-linear relationships and includes regularisation, which makes it a popular choice for stock price prediction.
- The original code used a random train/test split, which lets the model see days on both sides of each test day; that inflates the scores.
- With a time-ordered split, XGBoost on price levels failed badly (MAPE 28%) because trees cannot predict prices above the range they were trained on.
- Predicting next-day returns instead fixed that, but the model only matched a naive “no change” forecast and its direction accuracy (54.1%) was barely above always predicting “up” (53.9%).
- Always compare a market prediction model with a naive baseline before trusting its metrics.
What is the XGBoost algorithm?
XGBoost, short for eXtreme Gradient Boosting, is a powerful machine-learning algorithm that has been gaining significant attention in recent years. XGBoost is an ensemble technique that uses a collection of decision trees to make predictions. It is particularly effective in handling large datasets and can efficiently manage missing values, outliers, and multicollinearity.
The Nifty features dataset
The dataset used for the implementation of the model is the NIFTY_EOD.csv file, which consists of open, high, low ,close, volume, PClose, lreg5, lreg7, lreg9, hma5, hma7, hma9, trsi, atr values for a particular stock.
Download the XGBost Regression Features Dataset prepared using Amibroker
Download NIFTY EOD csv data set
Each row has the day’s OHLC and volume, the previous close, linear regression values (lreg5/7/9), Hull moving averages (hma5/7/9), a trend RSI and ATR. The target column close_forecast is the next trading day’s close. The data runs from September 1992 to April 2023. If you want to build your own features file, see preparing the features dataset using AmiBroker exploration.
Why XGBoost is better than linear regression
Non-linearity: Unlike linear regression, which assumes a linear relationship between features and the target variable, XGBoost can model complex, non-linear relationships. This is particularly helpful for predicting stock market direction, as the underlying relationships between variables are often non-linear.
Robustness: XGBoost is more robust to noise and outliers in the data compared to linear regression. This makes the algorithm better suited for predicting market direction, which can be influenced by various factors that are not always apparent in the historical data.
Regularization: XGBoost includes regularization, which helps prevent overfitting by penalizing complex models. This helps the algorithm generalize better to new data, making it more reliable for predicting market direction.
Handling missing values: XGBoost can automatically handle missing values, making it easier to work with incomplete datasets. In contrast, linear regression often requires imputation or other preprocessing techniques to handle missing values.
Python code for XGBoost stock market prediction
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_percentage_error, mean_squared_error, r2_score, explained_variance_score, mean_absolute_error
import matplotlib.pyplot as plt
import seaborn as sns
# Load the data
stock = pd.read_csv("NIFTY_EOD.csv")
data = stock
# Split the data into features and target
y = data['close_forecast']
X = data.drop(columns=['Ticker','Date/Time','close_forecast'], axis=1)
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train an XGBoost model
model = xgb.XGBRegressor(objective='reg:squarederror', random_state=42, booster='gbtree')
model.fit(X_train, y_train)
# Predict on the test set
y_pred = model.predict(X_test)
# Add predicted prices to test data
predicted_prices = X_test.copy()
predicted_prices['Close'] = y_pred
# Calculate evaluation metrics
mape = mean_absolute_percentage_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
explained_var = explained_variance_score(y_test, y_pred)
# Print the evaluation metrics and directional accuracy
print("MAPE:", mape)
print("Mean squared error:", mse)
print("Root mean squared error:", rmse)
print("Mean absolute error:", mae)
print("R-squared:", r2)
print("Explained variance:", explained_var)
# Predict the next day close and direction
next_day = X.tail(1)
next_day_pred = model.predict(next_day)
next_day_close = next_day_pred[0]
print("Next day predicted close:", next_day_close)
# Store the predicted vs actual values and direction in a separate csv
predictions = pd.DataFrame({'Date/Time': X_test.index, 'Actual': y_test.values, 'Predicted': y_pred})
predictions.to_csv("NIFTY_xgboost_predictions.csv", index=False)
# Plot feature importance using Matplotlib
fig, ax = plt.subplots(figsize=(10, 8))
xgb.plot_importance(model, ax=ax, importance_type='gain')
plt.title('Feature Importance')
plt.show()
The provided Python code imports necessary libraries loads NIFTY historical data, and preprocesses the dataset. It then splits the data into training and test sets and trains an XGBoost model. The model’s performance is evaluated using various metrics, including mean absolute percentage error (MAPE), mean squared error (MSE), root mean squared error (RMSE), mean absolute error (MAE), R-squared, explained variance, and directional accuracy. The code then predicts the next day’s NIFTY close and direction.
Python output
MAPE: 0.012514069979435037
Mean squared error: 7843.5028405418425
Root mean squared error: 88.56355255149741
Mean absolute error: 52.471655232747395
R-squared: 0.9996397979447728
Explained variance: 0.9996400254819038
Next day predicted close: 17407.646
Output and interpretation
The output metrics for the XGBoost prediction algorithm provide valuable insights into the model’s performance in predicting the NIFTY close prices and market direction. Let’s analyze these metrics in detail:
- MAPE (Mean Absolute Percentage Error): 0.012514069979435037
- MAPE is a measure of prediction accuracy in a forecasting model, expressed as a percentage. It is calculated by taking the average of the absolute percentage errors. The value of 0.0125 means that, on average, the model’s predictions deviate by about 1.25% from the actual values.
- Mean Squared Error (MSE): 7843.5028405418425
- MSE is a measure of the difference between the predicted and actual values. It is calculated by taking the average of the squared differences between the predictions and actual values. A lower MSE indicates a better fit of the model. In this case, the MSE is 7843.5.
- Root Mean Squared Error (RMSE): 88.56355255149741
- RMSE is the square root of MSE. It is another measure of the differences between predicted and actual values, and it is useful because it has the same unit as the target variable. In this case, the RMSE is 88.56, which means that, on average, the model’s predictions are off by about 88.56 units from the actual values.
- Mean Absolute Error (MAE): 52.471655232747395
- MAE is the average of the absolute differences between the predicted and actual values. It is a measure of prediction accuracy that is less sensitive to large errors than MSE or RMSE. In this case, the MAE is 52.47, which means that, on average, the model’s predictions are off by about 52.47 units from the actual values.
- R-squared: 0.9996397979447728
- R-squared, also known as the coefficient of determination, is a measure of the proportion of the variance in the target variable that is predictable from the input features. It ranges from 0 to 1, with 1 indicating a perfect fit. In this case, the R-squared value of 0.9996 suggests that the model explains approximately 99.96% of the variation in the target variable.
- Explained Variance: 0.9996400254819038
- Explained variance is a measure of how well the model captures the variance in the target variable. It ranges from 0 to 1, with a higher value indicating better performance. In this case, the explained variance of 0.9996 suggests that the model captures approximately 99.96% of the variance in the target variable.
- Next day predicted close: 17407.646
- This is the predicted closing price of the stock for the next day based on the model’s forecast.
Feature importance
Feature importance values represent the relative contribution of each feature to the model’s prediction. In the context of the XGBoost algorithm, these values are computed based on the number of times a feature appears in the trees across all the decision trees and the improvement it brings to the model, typically measured by a metric like Gini impurity or information gain.

A small correction: Gini impurity and information gain are used by classification trees. For this regression model XGBoost’s “gain” is the reduction in the squared-error loss each split brings, averaged over the splits that use the feature.
The XGBoost algorithm offers significant advantages over linear regression for predicting the stock market and market direction, particularly in handling non-linear relationships and providing robustness against noise and outliers. The provided Python code demonstrates how to use XGBoost for predicting the next day’s NIFTY close and direction, and while the model performs well in predicting close prices, it may require further optimization to improve its ability to predict market direction.
Why the 0.9996 R-squared is misleading
An R-squared of 0.9996 sounds like a near-perfect model, but on price levels it is almost guaranteed. Tomorrow’s Nifty close is always very close to today’s, so any model that roughly copies today’s price explains nearly all the variance. Two more issues made the original numbers look better than they are:
- Random train/test split.
train_test_split(..., random_state=42)shuffles the days, so the model trains on days immediately before and after every test day. In live trading you never see the future, so the test must come strictly after the training period. - No baseline. The original post does not compare the model with the simplest forecast, “tomorrow = today”. Without it you cannot tell whether the model adds anything.
- Direction never measured. The text mentions directional accuracy, but the code does not compute it.
Generate a random market where nothing can be predicted. A forecast that simply repeats yesterday’s close still scores a near-perfect R-squared, while direction stays at a coin toss.
Updated version (2026): time-ordered split and a naive baseline
This version keeps the same data and model but trains on the first 80% of history and tests on the last 20% (March 2017 to April 2023). It also replaces mean_squared_error(..., squared=False), which no longer exists in current scikit-learn (it raises a TypeError in scikit-learn 1.9), with root_mean_squared_error, and it measures direction against the naive forecast. Tested with Python 3.13, xgboost 3.4 and scikit-learn 1.9.
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import (mean_absolute_percentage_error, root_mean_squared_error,
mean_absolute_error, r2_score)
# Load the AmiBroker export (close_forecast = next day's close)
data = pd.read_csv("NIFTY_EOD.csv")
data["Date/Time"] = pd.to_datetime(data["Date/Time"], format="%d-%m-%Y")
data = data.sort_values("Date/Time").set_index("Date/Time")
y = data["close_forecast"]
X = data.drop(columns=["Ticker", "close_forecast"])
# Time-ordered split: train on the past, test on the most recent 20%
split = int(len(data) * 0.8)
X_train, X_test = X.iloc[:split], X.iloc[split:]
y_train, y_test = y.iloc[:split], y.iloc[split:]
model = xgb.XGBRegressor(objective="reg:squarederror", n_estimators=300,
learning_rate=0.05, max_depth=4, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# Naive baseline: tomorrow's close = today's close
naive = X_test["Close"].values
print("XGBoost MAPE:", round(mean_absolute_percentage_error(y_test, y_pred), 4),
"RMSE:", round(root_mean_squared_error(y_test, y_pred), 2),
"MAE:", round(mean_absolute_error(y_test, y_pred), 2),
"R2:", round(r2_score(y_test, y_pred), 4))
print("Naive MAPE:", round(mean_absolute_percentage_error(y_test, naive), 4),
"RMSE:", round(root_mean_squared_error(y_test, naive), 2),
"MAE:", round(mean_absolute_error(y_test, naive), 2))
# Directional accuracy: did we call tomorrow up or down correctly?
actual_dir = np.sign(y_test.values - X_test["Close"].values)
pred_dir = np.sign(y_pred - X_test["Close"].values)
print("Directional accuracy:", round((actual_dir == pred_dir).mean(), 4))
print("Share of up days in test set:", round((actual_dir > 0).mean(), 4))
print("Test period:", X_test.index[0].date(), "to", X_test.index[-1].date())
print("Next day predicted close:", round(float(model.predict(X.tail(1))[0]), 2))
Output:
XGBoost MAPE: 0.2831 RMSE: 5179.61 MAE: 4167.31 R2: -1.874
Naive MAPE: 0.0076 RMSE: 139.73 MAE: 97.05
Directional accuracy: 0.4627
Share of up days in test set: 0.5387
Test period: 2017-03-16 to 2023-04-03
Next day predicted close: 8823.69
The result is the opposite of the original post. Nifty traded far above its 1992 to 2017 range during the test period, and decision trees cannot predict values outside the range of the training target, so the forecasts got stuck below the old highs (the “next day” forecast of 8,823 when Nifty was above 17,000). The naive forecast had an average error of 97 points; XGBoost’s was over 4,000.
Predicting returns instead of prices
The standard fix is to make the target and features scale-free: predict tomorrow’s percentage change and express each indicator as a distance from today’s close.
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_absolute_error
data = pd.read_csv("NIFTY_EOD.csv")
data["Date/Time"] = pd.to_datetime(data["Date/Time"], format="%d-%m-%Y")
data = data.sort_values("Date/Time").set_index("Date/Time")
# Scale-free features: distance of each indicator from today's close, in %
feat = pd.DataFrame(index=data.index)
for col in ["Open", "High", "Low", "PClose", "lreg5", "lreg7", "lreg9", "hma5", "hma7", "hma9"]:
feat[col + "_pct"] = data[col] / data["Close"] - 1
feat["atr_pct"] = data["atr"] / data["Close"]
feat["trsi"] = data["trsi"]
# Target: next day's return instead of next day's price level
target = data["close_forecast"] / data["Close"] - 1
split = int(len(data) * 0.8)
X_train, X_test = feat.iloc[:split], feat.iloc[split:]
y_train, y_test = target.iloc[:split], target.iloc[split:]
model = xgb.XGBRegressor(objective="reg:squarederror", n_estimators=300,
learning_rate=0.05, max_depth=3, random_state=42)
model.fit(X_train, y_train)
ret_pred = model.predict(X_test)
close_test = data["Close"].iloc[split:]
price_pred = close_test * (1 + ret_pred)
print("MAE in points (XGBoost on returns):", round(mean_absolute_error(data["close_forecast"].iloc[split:], price_pred), 2))
print("MAE in points (naive, no change): ", round(mean_absolute_error(data["close_forecast"].iloc[split:], close_test), 2))
print("Directional accuracy:", round((np.sign(ret_pred) == np.sign(y_test)).mean(), 4))
print("Always-up accuracy: ", round((y_test > 0).mean(), 4))
Output:
MAE in points (XGBoost on returns): 97.3
MAE in points (naive, no change): 97.05
Directional accuracy: 0.5413
Always-up accuracy: 0.5387
Now the errors are sensible, but the model is no better than the naive forecast (97.3 against 97.05 points), and its 54.1% direction hit rate is only 0.3 percentage points above simply predicting “up” every day in a rising market. That is the honest state of next-day prediction from price-derived indicators: very little edge, if any. To find real signal you usually need different information (breadth, options data, flows, cross-asset moves), a longer horizon, or a trading rule that profits from a small edge after costs. Tools such as SHAP help you check what the model is actually using.
How to make XGBoost stock market prediction more realistic
- Split by time, and use walk-forward validation (retrain every few months) rather than one split.
- Predict returns or direction, not price levels.
- Always report a naive baseline and an “always up” baseline next to your metrics.
- Convert predictions into a trading rule and backtest it with brokerage, STT and slippage.
- Keep features that are known at the close of the signal day only, to avoid look-ahead bias.
For the basics behind features and targets, read decoding features and targets in machine learning, and compare this post with AdaBoost for stock market prediction.
Frequently Asked Questions
Can XGBoost predict stock prices?
It can fit historical prices very closely, but out-of-sample next-day forecasts from price indicators are usually no better than assuming no change. It is more useful for predicting returns or direction as one input to a trading system.
Why is my XGBoost stock model R-squared so high?
Because consecutive prices are almost equal, so even a “tomorrow = today” forecast has an R-squared close to 1. A random train/test split makes it look even better. Compare against a naive baseline on a time-ordered test set.
Is XGBoost better than LSTM for stock prediction?
For tabular indicator features XGBoost is usually faster to train and as accurate. Neither overcomes the basic problem that daily price changes are mostly noise.
Why does XGBoost fail when the market makes new highs?
Decision trees predict values within the range seen in training. If the test period has prices above the training maximum, a price-level model cannot follow them. Predicting returns avoids this.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.


could you explain what are lreg5, lreg7, lreg9, hma5, hma7, hma9, trsi
linear regression, hull moving average and turbo rsi