Skip to content
AI14 min read

Machine Learning in Finance: Forecasting Methods, Evidence and a Tested Backtest

Machine learning can sharpen financial forecasts, but only when it beats a simple baseline in an honest, walk-forward test. Here is what the research shows, which methods fit which problems, where fraud, credit and trading models fit in, and a tested Python backtest that exposes the most common mistake.

By

Editor

Published

Updated

Cover image for “ML in financial forecasting”: Does it beat a simple baseline?, illustrated with a candlestick chart with a forecast line.

The short answer

Machine learning in financial forecasting means training models such as gradient-boosted trees, regularized regression or neural networks on historical data to predict figures like revenue, demand, cash flow, returns or economic growth. It helps most with many related series and rich features. It only earns its place when it beats simple baselines in a walk-forward backtest that never lets the model see the future.

Search for machine learning in financial forecasting and most results promise sharper accuracy and fewer errors, then stop before the part that decides whether any of it is true: how you test a forecast. Without that, a model that looks brilliant in a slide deck can be worse than a spreadsheet that repeats last quarter's number.

This guide covers what machine learning actually adds to forecasting, what the two largest public forecasting competitions found, which methods suit which problems, and the risks regulators care about. It also includes a short Python backtest we ran ourselves on 50 years of US economic data. It shows how a common testing shortcut makes models look better than they are, and how a well-tuned model can still lose to a simple average.

What is machine learning in financial forecasting?

Machine learning in financial forecasting is the use of models that learn patterns from historical data to predict future financial figures: revenue, unit demand, cash flow, expenses, default rates, asset returns or macroeconomic indicators such as GDP growth. Instead of an analyst writing the formula ("next quarter equals this quarter plus 3%"), the model works out how past values and drivers relate to what happened next.

Traditional statistical forecasting, such as exponential smoothing or ARIMA, usually models one series at a time from its own history. Machine learning tends to differ in two ways. It can learn from many series at once (thousands of products or branches), and it can take in many extra inputs, called features, such as prices, promotions, calendar effects or interest rates, and capture nonlinear interactions between them. If the basics of models, features and training are new to you, start with our machine learning for beginners guide.

One boundary is worth knowing early. A forecast answers "what will happen if things carry on as they are?" Planning questions, such as "what happens to sales if we raise prices 5%?", are causal. Researchers Helmut Wasserbacher and Martin Spindler point out in their review of machine learning for financial planning and analysis (opens in a new tab) that most traditional machine learning techniques focus on prediction, and that "the naive application of machine learning usually fails" for causal questions. They point to methods such as double machine learning for those.

Where machine learning is used in finance and banking

Forecasting shows up across finance functions. The table below maps common jobs to the methods teams typically reach for. It is a starting point, not a rule: the right choice depends on how much data you have and how stable the patterns are.

Common financial forecasting tasks and typical methods
TaskWhat is forecastTypical methodsWhat makes it hard
Demand and sales forecastingUnits or revenue by product, store or regionGradient-boosted trees (LightGBM), global models across many series, exponential smoothing as a baselinePromotions, holidays, intermittent sales, thousands of series
FP&A and budgetingRevenue, expenses, cash flow by month or quarterRegularized regression, exponential smoothing, boosting with driver featuresShort histories, one-off events, need to explain the numbers
Treasury and liquidityDaily cash positions, deposit flowsBoosting with calendar features, statistical baselinesCalendar effects, rare large movements
Credit riskDefault probability, expected lossesLogistic regression, gradient-boosted treesRegulation, explainability, economic cycles
Asset returnsStock or portfolio returnsTrees, neural networks, regularized regressionVery low signal-to-noise, costs, crowded signals
Macroeconomic forecastingGDP growth, inflation, unemploymentRegularized regression, factor models, boostingFew observations, recessions, structural breaks

What the evidence says: does machine learning beat statistics?

The most useful evidence comes from the M competitions run by Spyros Makridakis and colleagues, where many teams forecast the same data and are scored on results they could not see in advance. Two of them point in opposite directions, and the difference is the lesson.

M4: statistics and hybrids won

M4 asked teams to forecast 100,000 time series from many domains. The published results (opens in a new tab) comment on "the poor accuracy of the pure machine learning (ML) methods" submitted, and found that "all of the top-performing methods" were "combinations of mostly statistical methods". The winner, from Slawek Smyl, was a hybrid that mixes exponential smoothing formulas with a recurrent neural network, fitting both together. The organizers called it the biggest surprise of the competition.

M5: machine learning swept the board

M5 was different. It used Walmart's hierarchical unit sales, 42,840 related time series (opens in a new tab), with prices and calendar events. In the organizers' paper (opens in a new tab), 5,507 teams from 101 countries took part, and "all top-performing methods were both "pure" ML ones and significantly better than all statistical benchmarks". The winning team improved on the best benchmark by 22.4%, its entry was an average of several LightGBM models, and the authors note that most of the top methods they examined used LightGBM.

Markets are a third case. In a widely cited study, Gu, Kelly and Xiu (opens in a new tab) compared methods for predicting US stock returns. They identified "trees and neural networks" as the best performers, "in some cases doubling the performance of leading regression-based strategies", and traced the gains to nonlinear interactions between predictors. That is a real result, but it comes from careful academic work on decades of data, not from a quick model on price charts.

Machine learning forecasting methods compared

You do not need to know every algorithm. These five families cover almost all practical machine learning forecasting work.

Forecasting method families at a glance
MethodBest whenWatch out for
Naive and seasonal naive ("same as last period")Always, as the baseline every model must beatNothing: if a model cannot beat this, it is not adding value
Statistical (exponential smoothing, ARIMA)Few, short series with stable patternsCannot easily use many outside drivers
Regularized linear regression (ridge, lasso)Short, noisy series with a handful of drivers; when you must explain the outputMisses nonlinear effects unless you engineer them
Gradient-boosted trees (LightGBM, XGBoost, scikit-learn)Many related series, lots of features, nonlinear effectsNeeds lag features built by hand; overfits small datasets; cannot extrapolate beyond values seen in training
Neural networks (RNN, LSTM, transformers)Large datasets, many series, long historiesData-hungry, costly to tune, hardest to explain

Tree models do not understand time on their own. You turn a series into a table where each row holds what was known at a point in time (this quarter's value, last quarter's value, a rolling average) and the target is what happened next. scikit-learn's own lagged features example (opens in a new tab) shows this pattern with its HistGradientBoostingRegressor. Large language models are a separate topic: they are good at reading reports and earnings calls, but for numeric forecasting the methods above remain the workhorses. Our explainer on what an AI model is covers how these families relate.

A tested backtest: the shortcut that flatters your model

Here is a small, real experiment. We forecast next quarter's US real GDP growth from information available at the end of the current quarter, using the US macroeconomic dataset (opens in a new tab) that ships with statsmodels: 203 quarters from 1959 to 2009, compiled from Federal Reserve Bank of St. Louis and Bureau of Labor Statistics data. GDP growth is a hard target, which makes it a good test of whether a model adds anything.

We compare four forecasters: a naive one (next quarter equals this quarter), the historical average of everything seen so far, ridge regression, and gradient boosting. Each model sees the last four quarters of GDP growth and inflation plus unemployment and the Treasury bill rate. They are scored by mean absolute error (MAE) in percentage points of annualized growth.

The evaluation is the important part. We use walk-forward testing: train on everything up to a point, forecast the next six years, then move the cut-off forward and repeat. Rob Hyndman and George Athanasopoulos describe this in Forecasting: Principles and Practice (opens in a new tab) as "evaluation on a rolling forecasting origin", where "no future observations can be used in constructing the forecast." scikit-learn implements it as `TimeSeriesSplit` (opens in a new tab). Then we score the same quarters with ordinary shuffled cross-validation, the standard approach for data without a time order, to see what it does.

gdp_backtest.py: walk-forward vs shuffled cross-validation (tested with scikit-learn 1.9.1, statsmodels 0.15.0, pandas 3.0.5)
import numpy as np
import pandas as pd
from statsmodels.datasets import macrodata
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import RidgeCV
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# 1. Data: US quarterly macro data, 1959Q1 to 2009Q3
df = macrodata.load_pandas().data
df["gdp_growth"] = 400 * np.log(df["realgdp"]).diff()  # annualized, %

# 2. Features: only information known at the end of quarter t
feats = pd.DataFrame(index=df.index)
for lag in range(4):
    feats[f"gdp_lag{lag}"] = df["gdp_growth"].shift(lag)
    feats[f"infl_lag{lag}"] = df["infl"].shift(lag)
feats["unemp"] = df["unemp"]
feats["unemp_change"] = df["unemp"].diff()
feats["tbill"] = df["tbilrate"]
feats["tbill_change"] = df["tbilrate"].diff()

# 3. Target: next quarter's GDP growth (t+1)
y = df["gdp_growth"].shift(-1)
data = pd.concat([feats, y.rename("target")], axis=1).dropna()
X, y = data.drop(columns="target"), data["target"]
print(f"quarters usable: {len(X)}, features: {X.shape[1]}")

models = {
    "ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 20))),
    "boosting": HistGradientBoostingRegressor(max_depth=3, learning_rate=0.05,
                                              max_iter=200, random_state=0),
}

# 4. Walk-forward test windows: always train on the past, test on the next block
tscv = TimeSeriesSplit(n_splits=5, test_size=24)  # five 6-year test windows
rows = []
for train_idx, test_idx in tscv.split(X):
    X_tr, X_te = X.iloc[train_idx], X.iloc[test_idx]
    y_tr, y_te = y.iloc[train_idx], y.iloc[test_idx]
    row = {
        "test_start": int(df.loc[X_te.index[0], "year"]),
        "naive": mean_absolute_error(y_te, X_te["gdp_lag0"]),  # next = this quarter
        "hist_mean": mean_absolute_error(y_te, np.full(len(y_te), y_tr.mean())),
    }
    for name, model in models.items():
        row[name] = mean_absolute_error(y_te, model.fit(X_tr, y_tr).predict(X_te))
    rows.append(row)

res = pd.DataFrame(rows).set_index("test_start")
print("\nwalk-forward MAE by test window (percentage points):")
print(res.round(2).to_string())
print("walk-forward average:", res.mean().round(2).to_dict())

# 5. The trap: shuffled K-fold scores the SAME quarters, but lets each model
#    train on quarters that come after the ones it is predicting
test_quarters = np.concatenate([t for _, t in tscv.split(X)])
shuffled = KFold(n_splits=5, shuffle=True, random_state=0)
for name, model in models.items():
    pred = cross_val_predict(model, X, y, cv=shuffled)
    mae = mean_absolute_error(y.iloc[test_quarters], pred[test_quarters])
    print(f"shuffled-CV MAE, same quarters, {name}: {mae:.2f}")

Install the libraries with pip install scikit-learn statsmodels pandas and run the file. This is the output we got:

Output
quarters usable: 198, features: 12

walk-forward MAE by test window (percentage points):
            naive  hist_mean  ridge  boosting
test_start                                   
1979         3.83       3.85   2.85      3.01
1985         2.24       1.70   1.80      2.32
1991         1.66       1.32   1.71      2.31
1997         2.57       1.91   2.02      1.85
2003         2.02       2.16   2.46      2.51
walk-forward average: {'naive': 2.47, 'hist_mean': 2.19, 'ridge': 2.17, 'boosting': 2.4}
shuffled-CV MAE, same quarters, ridge: 1.99
shuffled-CV MAE, same quarters, boosting: 2.14
Average error over the same 120 forecast quarters (lower is better)
ForecasterWalk-forward MAEShuffled-CV MAEVerdict
Naive (this quarter repeats)2.47n/aWorst overall
Historical average2.19n/aThe bar to beat
Ridge regression2.171.99Ties the average in an honest test
Gradient boosting2.402.14Looks better than the average under shuffling, is worse in reality

Three lessons come out of a few seconds of compute:

  1. Shuffled cross-validation flattered both models. Scored on exactly the same quarters, it cut the error by 0.18 points for ridge and 0.26 for boosting, because each model was trained on quarters that came after the ones it was predicting. Under shuffling, boosting (2.14) looks better than the historical average (2.19). In an honest walk-forward test it is clearly worse (2.40).
  2. The baseline is the benchmark, not zero. A plain average of past growth was nearly as good as ridge regression and better than gradient boosting. Twelve features and a tuned model bought almost nothing on this problem.
  3. Errors move with the economy. The first window, which runs from late 1979 to 1985 and includes the early 1980s recessions, was hard for everyone. The last one, which ends in 2009, includes the financial crisis. No model saw that coming, and an average across windows hides that.

This is one dataset with about 200 observations, which is exactly the setting where M4 found statistics hard to beat. With thousands of related series and rich features, as in M5, boosting would likely win. The point is not that machine learning fails. It is that you only find out which case you are in by testing it properly.

A practical workflow for AI financial forecasting

  1. Define the decision. What figure, at what level (product, store, entity), how far ahead, and what accuracy would change a decision? A cash forecast 13 weeks out is a different problem from next year's budget.
  2. Build the baselines first. Naive, seasonal naive and a simple statistical model. Record their walk-forward errors. These are the numbers to beat.
  3. Assemble point-in-time data. Each row may only hold what was known at the forecast date. Watch out for revised figures: economic data and accounting numbers often change after first release, and training on final values leaks information you did not have.
  4. Engineer features. Lags, rolling averages, calendar effects, prices, promotions and leading indicators. Compute rolling statistics using past values only.
  5. Backtest walk-forward. Use rolling or expanding windows, and a gap between training and test data when your target overlaps periods. Score on several windows, including a downturn if you have one.
  6. Pick a metric that matches the cost. MAE for typical error, a percentage error for comparisons across series, and prediction intervals or quantile forecasts when the downside matters more than the average.
  7. Combine and explain. Averages of several models are often more accurate and more stable than any single one, which both M competitions support. Use feature importance or SHAP-style explanations so finance owners can challenge the drivers.
  8. Monitor in production. Compare forecasts with actuals every period, track drift in inputs, and set a rule for when to retrain or fall back to the baseline.

If you are deciding between building and buying, the same checklist applies to a vendor's tool: ask for its walk-forward errors against a naive baseline on your data. For how training and fine-tuning work more broadly, see our guide to AI model training.

Eight-step workflow for machine learning in financial forecasting: define the decision, build baselines first, assemble point-in-time data, engineer features, backtest walk-forward, choose a metric, combine and explain models, and monitor in production.
A practical workflow for machine learning forecasts in finance.

Machine learning in finance beyond forecasting: fraud, credit scoring and trading

Forecasting is only one part of machine learning in finance. The same model families do much of their work in three other places. In the Bank of England and FCA survey of AI in UK financial services (opens in a new tab), published in 2024 with 118 firms responding, 75% of firms said they were already using AI, and gradient boosting was the most common model type, at 32%.

  • Fraud and money laundering detection. Models score payments as they happen and flag unusual patterns. The BIS FSI Insights paper (opens in a new tab) lists real-time monitoring of unauthorized credit card transactions as a use case, and describes AI tools that help by "flagging the rapid movement of money into different accounts". In the UK survey, 33% of respondents used AI for fraud detection and a further 31% expected to within three years.
  • Credit scoring. The same BIS paper notes that machine learning "has been used for many years in credit underwriting", for scoring, valuing collateral and setting interest rates. The accuracy evidence is mixed. A benchmark of 41 classifiers on seven credit scoring datasets (opens in a new tab) by Lessmann, Seow, Baesens and Thomas found the best performer was an ensemble method in six of the seven, while the Financial Stability Board's 2017 report on AI and machine learning in financial services (opens in a new tab) said it had "not yet been proved" that machine learning scorecards outperform traditional ones. Because a lender must be able to justify each decision, the explainability concerns below apply with extra force here.
  • Trading and investing. The FSB report describes trading firms using machine learning to improve their ability to sell to clients and investigating AI tools "to assess the market impact of a given trade" before placing it. Systematic investors use it to predict returns, the setting of the Gu, Kelly and Xiu study above.

All three share the core lesson of this guide. A fraud model has to be judged on transactions it has not seen, a scorecard on loans that have had time to default, and a trading signal on later periods than the ones it learned from, so the walk-forward discipline in the backtest above carries straight over.

Risks: overfitting, regime change, explainability and regulation

  • Data leakage and overfitting. As the backtest above shows, small evaluation mistakes produce large, false gains. Trying hundreds of model variants and keeping the best one is its own form of overfitting, so hold back a final test period you touch only once.
  • Regime change. Models learn the relationships in their training data. Rate shocks, pandemics or new regulation can break those relationships overnight, and tree models cannot extrapolate beyond the values they have seen.
  • Explainability. The Bank for International Settlements' FSI Insights paper on regulating AI in finance (opens in a new tab) says AI may heighten existing risks such as model risk, and that "heightened model risk can be caused by lack of explainability of AI models."
  • Model risk governance. In the US, bank supervisors' revised guidance on model risk management (opens in a new tab) (SR 26-2, issued in April 2026 by the Federal Reserve, OCC and FDIC, which replaced 2011's SR 11-7) sets out what they expect when banks rely on models. It calls for validation, ongoing monitoring and outcomes analysis, including back-testing that compares model outputs with real-world outcomes.
  • Causal misuse. A forecasting model that predicts well is not proof that changing a driver will change the outcome. Use causal methods for what-if planning.
the potential for adverse financial consequences associated with models
Federal Reserve, OCC and FDIC, SR 26-2, defining model risk

The guidance also asks for "effective challenge": critical analysis by objective experts who can spot a model's limits and get them fixed. That is good practice for any finance team, regulated or not. If you are rolling AI out more widely in a finance function, our guide to AI agents for business covers governance questions that carry over.

The bottom line

Machine learning in financial forecasting works best where M5 pointed: many related series, long histories and informative drivers, with gradient-boosted trees as the strong default. On short, noisy series such as quarterly GDP, simple baselines and regularized regression are hard to beat, as our backtest showed. Whatever you build, judge it walk-forward against a naive forecast, never with shuffled cross-validation, and keep monitoring it against actuals. To go deeper on the skills involved, see how to learn machine learning, or browse all our AI guides.

Common questions

How is machine learning used in financial forecasting?

Teams use it to forecast sales and demand, cash flow, expenses, credit losses, asset returns and economic indicators. The model learns patterns from past values plus related drivers, such as prices, promotions or interest rates, and produces a forecast for the next period or several periods ahead.

Is machine learning better than traditional forecasting methods?

It depends on the data. In the M4 competition, pure machine learning methods were inaccurate and the leaders were mostly combinations of statistical methods, while in the M5 retail competition every top method was pure machine learning and beat all statistical benchmarks. Test both on your own data before deciding.

Which machine learning model is best for financial forecasting?

There is no single best model. Gradient-boosted trees such as LightGBM are a strong default when you have many related series and lots of features, regularized linear regression is hard to beat on short, noisy series, and neural networks pay off mainly with large datasets.

How is machine learning used in finance beyond forecasting?

The biggest uses are fraud and money laundering detection, credit scoring and underwriting, and trading, where firms use it to estimate the market impact of trades and to predict returns. In a Bank of England and FCA survey, a third of UK firms said they already used AI for fraud detection.

Can machine learning predict the stock market?

Research such as Gu, Kelly and Xiu found that trees and neural networks improved return predictions over regression-based strategies, but predictive gains in markets are small, unstable and easily erased by costs or overfitting. No model removes the risk of loss.

What are the main risks of machine learning in finance?

The big ones are data leakage and overfitting in backtests, regime changes that break learned patterns, weak explainability, and model risk from decisions built on wrong or misused outputs. Bank supervisors expect independent validation and ongoing monitoring for models like these.

Sources

  1. The M4 Competition: 100,000 time series and 61 forecasting methods, International Journal of Forecasting (Makridakis, Spiliotis, Assimakopoulos)
  2. M5 accuracy competition: Results, findings, and conclusions, International Journal of Forecasting, via EconPapers (Makridakis, Spiliotis, Assimakopoulos)
  3. The M5 Accuracy competition: Results, findings and conclusions (preprint), Makridakis, Spiliotis, Assimakopoulos, hosted by Columbia University Statistical Modeling blog
  4. Empirical Asset Pricing via Machine Learning, National Bureau of Economic Research (Gu, Kelly, Xiu)
  5. Machine Learning for Financial Forecasting, Planning and Analysis: Recent Developments and Pitfalls, arXiv (Wasserbacher, Spindler)
  6. Time series cross-validation, Forecasting: Principles and Practice, OTexts (Hyndman, Athanasopoulos)
  7. TimeSeriesSplit, scikit-learn documentation
  8. Lagged features for time series forecasting, scikit-learn documentation
  9. United States Macroeconomic data, statsmodels documentation
  10. SR 26-2: Revised Guidance on Model Risk Management, Board of Governors of the Federal Reserve System, with the OCC and FDIC
  11. Regulating AI in the financial sector: recent developments and main challenges, Bank for International Settlements, FSI Insights No 63
  12. Artificial intelligence in UK financial services - 2024, Bank of England and Financial Conduct Authority
  13. Artificial intelligence and machine learning in financial services, Financial Stability Board
  14. Benchmarking state-of-the-art classification algorithms for credit scoring: A ten-year update, Lessmann, Seow, Baesens and Thomas, hosted by the University of Edinburgh Credit Research Centre

Revision history

  • : Retitled the guide around machine learning in finance, added a section and FAQ on fraud detection, credit scoring and trading with new sources, and re-ran the backtest to confirm its output.
  • : Updated the model risk section for SR 26-2, the April 2026 interagency guidance that replaced the Federal Reserve's SR 11-7.

About Marcus E.

Qualified software engineer with 10+ years of experience building payments and machine learning infrastructure

Marcus is a qualified software engineer who spent 10+ years building payment and machine learning infrastructure before joining GeeklyPlug. He writes AI and technology guides, with a focus on models, machine learning and the tools developers use.

machine learningfinanceforecastingpython

Keep reading

More from AI, then the rest of the archive.