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.

We are Azumo
and we get it

We understand the struggle of finding the right software development team to build your service or solution.

Since our founding in 2016 we have heard countless horror stories of the vanishing developer, the never-ending late night conference calls with the offshore dev team, and the mounting frustration of dealing with buggy code, missed deadlines and poor communication. We built Azumo to solve those problems and offer you more. We deliver well trained, senior developers, excited to work, communicate and build software together that will advance your business.

Want to see how we can deliver for you?

schedule my call

Benefits You Can Expect

Release software features faster and maintain apps with Azumo. Our developers are not freelancers and we are not a marketplace. We take pride in our work and seat dedicated Azumo engineers with you who take ownership of the project and create valuable solutions for you.

Industry Experts

Businesses across industries trust Azumo. Our expertise spans industries from healthcare, finance, retail, e-commerce, media, education, manufacturing and more.

Illustration of globe for technology nearshore software development outsourcing

Real-Time Collaboration

Enjoy seamless collaboration with our time zone-aligned developers. Collaborate, brainstorm, and share feedback easily during your working hours.

vCTO Solution Illustration

Boost Velocity

Increase your development speed. Scale your team up or down as you need with confidence, so you can meet deadlines and market demand without compromise.

Illustration of bullseye for technology nearshore software development outsourcing

Agile Approach

We adhere to strict project management principles that guarantee outstanding software development results.

Quality Code

Benefits from our commitment to quality. Our developers receive continuous training, so they can deliver top-notch code.

Flexible Models

Our engagement models allow you to tailor our services to your budget, so you get the most value for your investment.

Client Testimonials

Zynga

Azumo has been great to work with. Their team has impressed us with their professionalism and capacity. We have a mature and sophisticated tech stack, and they were able to jump in and rapidly make valuable contributions.

Zynga
Drew Heidgerken
Director of Engineering
Zaplabs

We worked with Azumo to help us staff up our custom software platform redevelopment efforts and they delivered everything we needed.

Zaplabs
James Wilson
President
Discovery Channel

The work was highly complicated and required a lot of planning, engineering, and customization. Their development knowledge is impressive.

Discovery Channel
Costa Constantinou
Senior Product Manager
Twitter

Azumo helped my team with the rapid development of a standalone app at Twitter and were incredibly thorough and detail oriented, resulting in a very solid product.

Twitter
Seth Harris
Senior Program Manager
Wine Enthusiast

Azumo's staff augmentation service has greatly expanded our digital custom publishing capabilities. Projects as diverse as Skills for Amazon Alexa to database-driven mobile apps are handled quickly, professionally and error free.

Wine Enthusiast Magazine
Greg Remillard
Executive Director
Zemax

So much of a successful Cloud development project is the listening. The Azumo team listens. They clearly understood the request and quickly provided solid answers.

Zemax
Matt Sutton
Head of Product

How it Works

schedule my call

Step 1: Schedule your call

Find a time convenient for you to discuss your needs and goals

Step 2: We review the details

We estimate the effort, design the team, and propose a solution for you to collaborate.

Step 3: Design, Build, Launch, Maintain

Seamlessly partner with us to confidently build software nearshore

We Deliver Every Sprint

Time Zone Aligned Developers

Our nearshore developers collaborate with you throughout your working day.

Experienced Engineers

We hire mid-career software development professionals and invest in them.

Transparent Communication

Good software is built on top of honest, english-always communication.

We Build Like Owners

We boost velocity by taking a problem solvers approach to software development.

You Get Consistent Results

Our internal quality assurance process ensures we push good working code.

Agile Project Management

We follow strict project management principles so we remain aligned to your goals