How to Build a Bitcoin Price Predictor with LSTM

Build your own Bitcoin price predictor using LSTM in Python. This step-by-step guide includes code, charts, and real market data for beginners.

Curious if you can build a Bitcoin price predictor that actually works?

In this guide, I’ll show you how to create a deep learning model using LSTM in Python to forecast Bitcoin prices. Whether you’re a data science beginner or a crypto enthusiast, you’ll walk away with a fully functional Bitcoin price predictor, complete with code, charts, and real market insights.

Let’s dive in and turn data into foresight.


🧾 What You’ll Learn

By the end of this tutorial, you’ll know how to:

  • Prepare and normalize time-series data for LSTM
  • Build and train an LSTM model using TensorFlow/Keras
  • Visualize training loss and predictions
  • Rescale predictions back to real prices
  • Evaluate the model’s performance

Let’s dive right in.


📊 Step 1: Load Bitcoin Data for Your Price Predictor

First, load your data and take a quick look at how Bitcoin prices have changed over time.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("bitcoin.csv")
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

# Plot the price
plt.figure(figsize=(14, 7))
plt.plot(df['Price'], label='Bitcoin Price', color='blue')
plt.title('Bitcoin Price Over Time')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()

🧼 Step 2: Normalize Data for the Bitcoin Price Predictor

Neural networks perform better when features are scaled. We’ll use MinMaxScaler to normalize the Bitcoin prices between 0 and 1.

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler(feature_range=(0, 1))
df['Price'] = scaler.fit_transform(df[['Price']])

📐 Step 3: Create Sequences for LSTM Input

LSTM networks work best with sequences. We’ll take the past 60 days of prices to predict the next day’s price.

import numpy as np

def create_sequences(data, seq_length):
sequences = []
labels = []
for i in range(len(data) - seq_length):
sequences.append(data[i:i+seq_length])
labels.append(data[i+seq_length])
return np.array(sequences), np.array(labels)

seq_length = 60
X, y = create_sequences(df['Price'].values, seq_length)

🧪 Step 4: Split Data into Training and Test Sets

We’ll keep 80% of the data for training and the rest for testing.

train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]

Note: LSTM expects 3D input: [samples, timesteps, features]. Let’s reshape that next.

X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))

🧠 Step 5: Build the LSTM-Based Bitcoin Price Predictor

Time for the fun part — building the LSTM model using TensorFlow/Keras.

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout

model = Sequential([
LSTM(50, return_sequences=True, input_shape=(seq_length, 1)),
Dropout(0.2),
LSTM(50, return_sequences=False),
Dropout(0.2),
Dense(25),
Dense(1)
])

⚙️ Step 6: Compile and Train the Model

model.compile(optimizer='adam', loss='mean_squared_error')

history = model.fit(
X_train, y_train,
epochs=20,
batch_size=16,
validation_data=(X_test, y_test)
)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training vs Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()

📈 Step 7: Let the Bitcoin Price Predictor Make Forecasts

Now, let’s make predictions and convert them back to their original scale.

y_pred = model.predict(X_test)
y_pred = scaler.inverse_transform(y_pred.reshape(-1, 1))
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))

🧾 Step 8: Plot Actual vs Predicted Prices

Let’s see how our model performed visually.

plt.figure(figsize=(14, 7))
plt.plot(y_test, label='Actual Price', color='blue')
plt.plot(y_pred, label='Predicted Price', color='red')
plt.title('Bitcoin Price Prediction')
plt.xlabel('Days')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()

✅ Final Thoughts on your Bitcoin Price Predictor

This LSTM-based approach gives a solid starting point for Bitcoin price prediction. While it’s not flawless (remember, crypto is volatile!), it captures underlying trends surprisingly well.

You’ve now learned how to:

  • Preprocess time-series data
  • Build and train an LSTM model
  • Evaluate and visualize predictions

Want to improve it? Try:

  • Tuning hyperparameters
  • Using additional features like volume or sentiment
  • Adding attention mechanisms

📢 What’s Next?

If you found this helpful, share this post, drop a comment, or explore Ossels AI to see how we can help bring AI solutions like this to your business.

Or hey — try this with Ethereum next?

Posted by Ananya Rajeev

Ananya Rajeev is a Kerala-born data scientist and AI enthusiast who simplifies generative and agentic AI for curious minds. B.Tech grad, code lover, and storyteller at heart.