AI and Machine Learning

Build a Web App for Real-Time Bitcoin & Ethereum Price Prediction

This article guides you through building a real-time Bitcoin and Ethereum price prediction web app using Python, Django, and TensorFlow. Learn to fetch live cryptocurrency data, create a machine learning model, and integrate predictions into a user-friendly interface. Perfect for exploring the intersection of web development, machine learning, and financial technology.

Benjamin Rivera
December 31, 2024

Bitcoin and Ethereum are two of the most popular cryptocurrencies in the world. Their prices change quickly, creating opportunities for traders and investors. What if you could build a web app that predicts these price changes in real-time?

In this article, we'll show you how to create a simple app using Python, Django, and TensorFlow. You’ll learn about the tools we use, and how they work together, and see some sample code. By the end, you’ll have a clear idea of how to get started on your own project.

What Are We Building?

We’re creating a web app that:

  1. Fetches live Bitcoin (BTC) and Ethereum (ETH) prices.
  2. Uses a machine learning model to predict future prices based on past data.
  3. Displays the results in a user-friendly interface.

Why Build This App?

  • Helps investors: Provides insights into price trends.
  • Learn key technologies: Combines web development and machine learning.
  • Real-world application: Explore how tech is used in finance.

Tools We’ll Use

  • Python: Programming language for data processing and backend logic.
  • Django: Web framework to create and run the app.
  • TensorFlow: A library to train and run the machine learning model.
  • SQLite/PostgreSQL: Stores historical cryptocurrency data.
  • CoinGecko API: Provides real-time BTC and ETH prices.
  • Plotly/Matplotlib: Visualizes historical and predicted prices.

Development Guide

1. Set Up the Project

pip install django tensorflow requests matplotlib pandas numpy

Create a new Django project and app:

django-admin startproject crypto_prediction  cd crypto_prediction  python manage.py startapp predictor  python manage.py migrate

2. Fetch Live Cryptocurrency Prices

You’ll use the CoinGecko API to get live prices for Bitcoin and Ethereum.

import requests  

def fetch_prices():  
    url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd"  
    response = requests.get(url)  
    if response.status_code == 200:  
        data = response.json()  
        return {  
            "BTC": data["bitcoin"]["usd"],  
            "ETH": data["ethereum"]["usd"]  
        }  
    else:  
        raise Exception("Failed to fetch data.")  

# Example usage  
print(fetch_prices())  # Output: {'BTC': 40000, 'ETH': 2500}

3. Build the Machine Learning Model

You’ll create a model using LSTM (Long Short-Term Memory), which works well for time-series data like price trends.

Prepare the Data

import pandas as pd  
import numpy as np  
from sklearn.preprocessing import MinMaxScaler  

# Load historical price data (replace this with API data in production)  
data = pd.read_csv("crypto_prices.csv")  

# Scale data between 0 and 1 for better performance  
scaler = MinMaxScaler()  
scaled_data = scaler.fit_transform(data["Close"].values.reshape(-1, 1))  

# Prepare data for the LSTM model  
def create_dataset(data, look_back=60):  
    X, y = [], []  
    for i in range(look_back, len(data)):  
        X.append(data[i-look_back:i, 0])  
        y.append(data[i, 0])  
    return np.array(X), np.array(y)  

X_train, y_train = create_dataset(scaled_data)  
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

Train the Model

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

model = Sequential()  
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))  
model.add(Dropout(0.2))  
model.add(LSTM(50, return_sequences=False))  
model.add(Dropout(0.2))  
model.add(Dense(1))  

model.compile(optimizer="adam", loss="mean_squared_error")  
model.fit(X_train, y_train, epochs=20, batch_size=32)  

# Save the model for later use  
model.save("crypto_model.h5")

4. Add Django Views for Predictions

Now, integrate the model into your Django app to make predictions.

from django.shortcuts import render  
from tensorflow.keras.models import load_model  
import numpy as np  

model = load_model("crypto_model.h5")  

def predict_prices(request):  
    prices = fetch_prices()  
    # Example prediction: replace this with actual live data preprocessing  
    input_data = np.array([[prices["BTC"], prices["ETH"]]])  
    input_data = np.reshape(input_data, (1, input_data.shape[1], 1))  
    prediction = model.predict(input_data)  

    return render(request, "predict.html", {"prediction": prediction})

5. Visualize Predictions with Plotly

Add charts to make predictions easier to understand.

import plotly.graph_objects as go  

def plot_prices(historical, predicted):  
    fig = go.Figure()  
    fig.add_trace(go.Scatter(y=historical, mode='lines', name="Historical Prices"))  
    fig.add_trace(go.Scatter(y=predicted, mode='lines', name="Predicted Prices"))  
    fig.update_layout(title="Bitcoin & Ethereum Prices", xaxis_title="Time", yaxis_title="Price (USD)")  
    return fig.to_html()

Final Thoughts

Building a web application for real-time cryptocurrency price prediction is an excellent way to explore the intersection of web development, machine learning, and financial technology. While this project is functional, there are several considerations and improvements that could make it even more robust and useful:

Considerations

  1. Data Reliability:
    The accuracy of the predictions depends heavily on the quality of the data. Real-time prices can fluctuate due to multiple factors like market sentiment, news, or global events. It's essential to fetch data from reliable sources like CoinGecko or Binance.
  2. Model Performance:
    Machine learning models are only as good as the data and features provided. The LSTM model used here works well for time-series data, but it may struggle with unexpected market volatility. Experimenting with additional models like GRUs or Transformer-based architectures could provide better results.
  3. Latency and Scalability:
    Predictions are made in real-time, so the system needs to process data quickly. For a production-ready application, consider optimizing server performance, caching responses, or deploying the model to a cloud service like AWS Sagemaker or Azure ML.‍
  4. Security:Handling APIs and sensitive user data requires proper security measures. Ensure API keys are stored securely, use HTTPS, and follow best practices for web application security.