Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to the guide
THE FINANCEBASE List yours

Guide

Bitcoin Price Prediction With RNNs and LSTMs: A Practical, Rigorous Guide

By TheFinanceBase Team 11 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recurrent neural networks (RNNs), including long short-term memory (LSTM) networks, can model sequences of Bitcoin market data—but they cannot reliably tell you what Bitcoin will be worth next or guarantee profitable trades. Their value depends less on the architecture than on a precise forecast target, clean timestamped data, leakage-free testing, strong baselines, and realistic trading costs.

This guide explains how to design a reproducible Bitcoin forecasting experiment, build an LSTM in Python, assess its uncertainty and performance, and decide whether the results justify further work. It is educational information, not investment advice.

As an Amazon Associate I earn from qualifying purchases.

What an RNN or LSTM can—and cannot—predict

An RNN processes observations in order and carries information from earlier time steps into a hidden state. An LSTM is a gated RNN: its forget, input, and output gates regulate what information is discarded, stored in a cell state, and passed forward. This can make it easier to learn patterns across a sequence than with a basic RNN, which can struggle with vanishing or exploding gradients over long sequences.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

That mechanism does not mean an LSTM understands Bitcoin’s causes, knows future news, or discovers a stable market law. It learns relationships in the historical data supplied to it. Its results remain sensitive to the exchange, candle interval, lookback window, features, target, training period, and market regime. Cryptocurrency forecasting research covers RNNs and LSTMs alongside CNNs, deep belief networks, and reinforcement learning, but the range of applications and methods is broad rather than a settled recipe (survey of deep-learning applications in cryptocurrency).

Studies have applied recurrent networks to Bitcoin price-direction prediction, but a result on one dataset or test period does not establish dependable performance elsewhere (Bitcoin price-direction study). A recent systematic review emphasizes the challenges posed by volatility and the need to assess robustness, not just reported accuracy (review of Bitcoin price forecasting).

Define the forecast before choosing a model

“Predict Bitcoin” is not a complete modeling problem. Specify the market, observation interval, forecast horizon, and exact value the model should estimate. A clear example is: “Predict the next hourly BTC-USD log return using the previous 48 completed hourly candles.” Also identify whether BTC-USD is spot data from one exchange or a different instrument, such as a futures or perpetual contract.

Choose a target

  • Price level: forecast the next close, a future high or low, or a price several intervals ahead. Price levels can produce deceptively low errors because adjacent prices are correlated and the series may trend.
  • Return: estimate a proportional change. Simple return is r_t = (P_t - P_{t-1}) / P_{t-1}; log return is r_t = log(P_t) - log(P_{t-1}). Returns are often more relevant to trading research, but generally noisier and harder to predict.
  • Direction: classify the next move as up or down, or as up, flat, or down. Define the threshold for “flat”; otherwise small price noise can determine the label.
  • Volatility: estimate future realized volatility, an absolute return, or a price range. This answers a different question from forecasting direction.
  • Trading action: map a forecast into a buy, sell, hold, or position-size decision. This requires an explicit execution and risk framework; it is not the same as forecasting.

Never report “accuracy” without the target, horizon, exchange or market, quote currency, candle interval, and test dates. For returns, a model that predicts zero can be a meaningful baseline; for price levels, a natural starting point is predicting that the next price equals the current one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose and audit the Bitcoin data

For a first experiment, use timestamped open, high, low, close, and volume (OHLCV) candles for one clearly identified market. Starting with one exchange makes the data easier to reproduce, although that market may not represent Bitcoin prices or liquidity everywhere. Record whether the instrument is spot, futures, or perpetual, and do not silently combine exchange prices.

Coinbase’s Advanced Trade public product-candle endpoint documents candle fields, granularities, and a maximum of 350 candle buckets per request (public product-candle documentation). Its documented granularities include one, five, fifteen, and thirty minutes; one, two, four, and six hours; and one day (candle granularity reference). Plan requests and pagination around endpoint limits rather than assuming a single request returns a long history. Coinbase distinguishes REST market-data endpoints from WebSocket feeds intended for faster real-time market and trade updates (Advanced Trade REST API documentation).

For reproducibility, document the provider and product symbol, time zone, candle interval and boundary convention, download date, start and end timestamps, missing-data handling, and any transformations. Historical candle data may omit intervals with no ticks; Coinbase’s Exchange documentation notes this limitation (product candles documentation). A missing candle is not automatically a zero-volume candle or permission to carry the previous close forward.

Add features only when their timing is defensible

After a basic OHLCV model, you can test lagged returns, rolling volatility, moving averages, RSI, MACD, Bollinger-band measures, volume changes, order-book imbalance, funding rates, open interest, cross-asset returns, macroeconomic series, sentiment, or on-chain activity. Add features incrementally and compare results under the same test design. Each new source introduces risks including timestamp mismatch, revisions, exchange-specific artifacts, survivorship bias, and overfitting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Only use information that would have been available at the forecast time. For example, a daily sentiment score published after a candle closes cannot be used to forecast that same close. Technical indicators must likewise be computed from observations available before the target period.

Build a leakage-resistant experiment

  1. State the forecast precisely. Specify the market, candle interval, lookback, target formula, and horizon. For example: next hourly log return from the prior 48 completed hourly candles.
  2. Sort and inspect timestamps. Sort chronologically, remove duplicate timestamps, identify gaps, and establish whether each timestamp marks a candle’s start or close. Investigate missing intervals rather than blindly forward-filling OHLC values.
  3. Create the target with the intended timing. For a next-period log return, one possible construction is df["target"] = np.log(df["close"]).diff().shift(-1). For the next close, use df["target"] = df["close"].shift(-1). Confirm against a few rows by hand, then drop rows without a target.
  4. Split chronologically. Use the earliest observations for training, a subsequent period for validation and model selection, and a final untouched period for testing. Do not shuffle time-series rows across these sets.
  5. Fit preprocessing on training data only. Fit the scaler, imputer, or feature-selection procedure using the training period; use the fitted transformation on validation and test data. Fitting a scaler on the complete dataset leaks future distribution information into training.
  6. Construct sequences without crossing the target boundary. Make each input window from observations available before its target. If you use earlier-period observations as context for a later test prediction, make that evaluation rule explicit and apply it consistently.
  7. Tune on validation data, then evaluate once on the test period. Repeatedly trying architectures or thresholds after inspecting test results turns the test set into part of model selection.
  8. For stronger evidence, use walk-forward evaluation. Train on an initial historical window, predict the next block, advance the window, and repeat. Aggregate predictions across folds; describe whether training expands or uses a rolling window and whether the model is refit at each step.

Common leakage sources include future values in rolling indicators, an incorrect label shift, using a candle close for a forecast supposedly made before that close, ignoring publication times for sentiment, tuning repeatedly on test results, and feeding actual future values into recursive forecasts. A recent Bitcoin trading study used multi-fold walk-forward evaluation and included transaction costs; in its particular setup, XGBoost was descriptively stronger than the tested LSTM and iTransformer alternatives, without establishing formal statistical dominance or a universal ranking (study and methods).

Establish baselines before training an LSTM

A complex network is only useful if it adds value over simpler alternatives tested on the same data, horizon, folds, and cost assumptions. Start with a small set of benchmarks:

  • Persistence: for a price-level forecast, predict the current price for the next period.
  • Zero return: for a return forecast, predict a zero next-period return.
  • Moving average or exponential smoothing: useful simple comparisons, especially for price-level forecasts.
  • ARIMA or a related statistical model: tests whether a neural network improves on a model of linear temporal structure.
  • Tree-based model: use lagged returns and other tabular features. The cited walk-forward comparison is a reminder that a tree model can outperform a neural model in a particular experiment, not proof it will do so in yours.

Compare a vanilla RNN with an LSTM if the architectural question matters. A GRU is another gated recurrent option, generally with a simpler structure and fewer parameters than an LSTM; a comparison paper reports differing results between GRU and LSTM rather than a universal winner (GRU and LSTM comparison). CNN-LSTM and Transformer models are possible extensions, but newer architecture does not itself imply better forecasts. Findings across methods can be difficult to compare because studies use different assets, periods, features, horizons, and evaluation designs (comparative review of cryptocurrency models).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Construct sequences and train an LSTM

For a lookback of 48, each example contains the previous 48 observations and the corresponding target. The resulting input has shape (samples, timesteps, features); for example, (20000, 48, 6) represents 20,000 samples, 48 candles per sample, and six features per candle.

def make_sequences(X, y, lookback):
    X_out, y_out = [], []
    for i in range(lookback, len(X)):
        X_out.append(X[i-lookback:i])
        y_out.append(y[i])
    return np.asarray(X_out), np.asarray(y_out)

Apply this logic within the chronological split boundaries so labels and windows are aligned as intended. Fit any scaler on the training features only, then transform the other sets using that fitted scaler:

scaler.fit(train_features)
X_train = scaler.transform(train_features)
X_valid = scaler.transform(valid_features)
X_test = scaler.transform(test_features)

For return forecasting, a compact Keras model could look like this:

model = keras.Sequential([
    keras.layers.Input(shape=(lookback, n_features)),
    keras.layers.LSTM(64, return_sequences=True),
    keras.layers.Dropout(0.2),
    keras.layers.LSTM(32),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(1)
])

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss="mse",
    metrics=[keras.metrics.MeanAbsoluteError()]
)

early_stop = keras.callbacks.EarlyStopping(
    monitor="val_loss",
    patience=10,
    restore_best_weights=True
)

This is an example configuration, not a validated optimum for Bitcoin. Treat layer count, units, dropout, learning rate, and lookback as hyperparameters. Select them on validation data, disclose the search procedure, and avoid a large search that effectively memorizes a small number of regimes. The official framework documentation describes the Keras LSTM layer and provides a time-series tutorial. PyTorch offers its own LSTM module and tutorials; framework choice does not create a forecasting edge by itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Evaluate forecast quality and uncertainty

Report metrics appropriate to the target and compare them with the baselines on the same held-out predictions. For a regression target, mean absolute error (MAE) is the average absolute difference, while root mean squared error (RMSE) penalizes large errors more heavily. MASE, median absolute error, correlation between predicted and realized returns, and directional accuracy can add context. For classification, consider balanced accuracy, precision, recall, F1, ROC-AUC, and probability calibration such as the Brier score. MAPE can be unstable or misleading when the target can be near zero, as returns often can.

A low RMSE or high R-squared on price levels does not demonstrate that a strategy is profitable. Price scale, horizon, and test period matter, so raw errors from different studies are not automatically comparable. Report performance by forecast horizon and, where practical, by market regime rather than relying on a single aggregate score.

Point forecasts also conceal uncertainty. Prediction intervals, quantile forecasts, ensembles, conformal prediction, or volatility-conditioned intervals can help show when a forecast is less certain. Check whether intervals are calibrated on genuinely out-of-sample observations; a narrow interval is not useful if it misses the realized outcome too often. Uncertainty should not be presented as constant through quiet and highly volatile periods without evidence.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test trading value separately from prediction error

A forecast becomes a trading strategy only after you define how it becomes a position and how that position is executed. Set a decision rule, such as a threshold on predicted return, before evaluating the final test period. Specify position sizing, trading frequency, exposure limits, and when an order is assumed to execute. A forecast made at candle close cannot be treated as filled at that same close unless the execution assumption supports it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Include commissions, spread, slippage, and, for relevant derivatives, funding. Report net cumulative and annualized return, annualized volatility, Sharpe and Sortino ratios, maximum drawdown, turnover, number of trades, hit rate, profit factor, exposure, and tail losses. State the fee and execution assumptions and how they apply. A model can have a small forecast error yet lose money after costs; a modest directional hit rate can also coexist with a profitable strategy if its gains and losses differ sufficiently in size.

Backtest results depend on assumptions about liquidity, fills, data availability, and costs. Treat them as evidence about a defined historical simulation, not a promise of future returns. Paper trading can test whether a signal and execution process behave as expected before risking capital, but it does not remove regime risk.

Handle multi-step forecasts and changing markets

A one-step forecast does not establish performance several periods ahead. For multi-step work, report each horizon separately and choose a method deliberately:

  • Direct forecasts: train a separate model for each horizon, such as one, six, or 24 periods ahead. This avoids feeding predictions back into the model but requires multiple models.
  • Recursive forecasts: predict one step, append the prediction, then predict the next. This is simple, but forecast errors can compound; do not substitute actual future observations during evaluation.
  • Sequence-to-sequence forecasts: train one model to output a future path. This can represent multiple horizons in one output but adds architectural and evaluation complexity.

Bitcoin market conditions change with liquidity, regulation, derivatives participation, exchange composition, macroeconomic conditions, technology, and sentiment. A model that fit one period can deteriorate in another. Walk-forward results, fold-by-fold reporting, and monitoring of forecast errors help reveal instability; they do not guarantee that future regimes will resemble past ones.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the experiment reproducible

Another analyst should be able to reconstruct the predictions without relying on an undocumented notebook state. Publish or record:

  • Raw-data source, retrieval date, market symbol, exchange, instrument type, time zone, interval, and date range.
  • Feature definitions, availability timestamps, target formula, forecast horizon, and lookback size.
  • Gap and duplicate handling, split dates, walk-forward rules, and scaling or imputation procedure.
  • Random seeds, software and environment versions, architecture, hyperparameter search space, stopping rule, and number of trials.
  • Out-of-sample predictions, evaluation metrics, and the trading assumptions for fees, spread, slippage, funding, and execution.

Preserve a final test period that remains untouched during model selection. If many experiments have already been tried against the same test period, a fresh period or a stronger nested evaluation is needed for a credible final estimate.

When an LSTM is a reasonable choice

An LSTM is worth testing when the question involves sequential relationships, you have enough consistently timestamped observations, and you can evaluate it against simpler methods with time-respecting splits. It is less compelling when a small dataset, limited compute, or a simple research question makes a baseline sufficient. More layers and more features can increase overfitting rather than improve evidence.

The strongest case for an LSTM is not that it has the highest score in one split, but that it adds repeatable out-of-sample value across multiple time periods, remains competitive after realistic costs if used for trading, and exposes uncertainty and failure modes clearly. Until those conditions are met, treat the output as an experimental forecast—not a dependable price target or an instruction to buy or sell.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a comment

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More guides

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.