Coins: 16,989
Exchanges: 1,292
Market Cap: $3.005T 4.4%
24h Vol: $142.021B
Gas: 1.321 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Build a Simple AI Model for Crypto Price Prediction

4.5
| by
Roxait
|
Edited by
Julia Ng
-

As crypto traders, we spend countless hours analyzing price charts, studying trends, and interpreting market indicators to spot opportunities. AI and machine learning can make this process faster and more efficient.

In this guide, we’ll build a simple predictive model for crypto prices using historical market data from the CoinGecko API. With full transparency and control, traders can fine-tune the model to fit their strategy and even automate trades with a crypto bot.


Prerequisites

Development Environment

Ensure that Node.js and npm are installed on your machine. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, and npm is the package manager for Node.js, used to manage your project's dependencies. You can download and install both from the Node.js official website.

Crypto Price & Market Data

We will use the CoinGecko API to fetch crypto prices and market data, especially the endpoint /market_chart. The free Demo plan is enough for our needs, with a rate limit of 30 calls per minute and a monthly cap of 10,000 calls. Create a Demo account today to try it out.

CoinGecko API Coins Market Data Endpoint

CoinGecko API

Python 3 and Pip

These need to be installed to begin developing and running AI models for your DeFi application.

Make sure Python 3 and pip are installed on your system. Python is used for AI model development, while pip helps you install the required Python libraries. You can check if Python and pip are installed by running python --version and pip --version in your terminal.

It's recommended to create a virtual environment to isolate your project's dependencies. This can prevent conflicts between packages required for different projects. 

Create a virtual environment by navigating to your project directory and executing python -m venv venv. Activate it with venv\Scripts\activate on Windows or source venv/bin/activate on macOS/Linux. Your terminal should now indicate that the environment is active.

Python Libraries

Next, install the necessary Python libraries by running:

pip install numpy pandas scikit-learn requests

This command installs the following packages:

  1. NumPy: A library for numerical computations with support for large, multi-dimensional arrays and matrices.
  2. Pandas: A library providing data structures and data analysis tools.
  3. scikit-learn: A machine learning library featuring various algorithms for classification, regression, clustering, and more.
  4. Requests: A simple HTTP library for making API requests, to fetch data from APIs like the CoinGecko API.

Node.js Modules

For the server-side development of your application, you'll need to install specific Node.js modules. Assuming you have Node.js and npm installed, you can install these modules using npm. In your terminal, run:

npm install express axios

Express is a web framework for Node.js that simplifies server creation, while axios is a promise-based HTTP client for making API requests.

npm install express axios python-shell dotenv

Initialize Node.js Project

In your project directory, use npm to initialize a new Node.js project, which will create a package.json file to manage project metadata and dependencies.

npm init -y

A package.json file is created with default values:

Initialize a Node.js Project

pip list, which should display the installed packages and their versions. Optionally, test your setup by creating a simple script (test_env.py) that imports these libraries and prints a confirmation message. Run the script with python test_env.py; if no errors occur, your Python environment is correctly set up.

Create a dedicated directory for your DeFAI project to keep your project organized. You can do this by running the below commands in your terminal

mkdir defi-ai-project
cd defi-ai-project

Your project directory should now look like:

defi-ai-project/

├── ai_model.py

├── data_collector.py

├── index.j

├── package.json

└── node_modules/


Step 1. Collect Market Data

We'll train our AI model with historical price data to provide insights into market trends and patterns. For this example, we’ll predict Bitcoin's price using its 30-day price history from the CoinGecko API. It's important to have clean, high-quality data since it impacts the model's performance. Using recent data also helps ensure it reflects current market behaviors.

In your project directory, create a file named data_collector.py:

import requests
import pandas as pd
import os
# Load environment variables
COINGECKO_API_KEY = "CG_API_KEY"
def fetch_market_data():
    url = 'https://pro-api.coingecko.com/api/v3/coins/bitcoin/market_chart'
    params = {
        'vs_currency': 'usd',
        'days': '30',  # Last 30 days
        'x_cg_pro_api_key': COINGECKO_API_KEY,
    }
    try:
        # Fetch data from CoinGecko API
        print("Fetching market data from CoinGecko...")
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        # Parse price and volume data
        prices = data.get('prices', [])
        volumes = data.get('total_volumes', [])
        print(f"Data points received: {len(prices)}")
        # Create DataFrame
        df_prices = pd.DataFrame(prices, columns=['timestamp', 'price'])
        df_volumes = pd.DataFrame(volumes, columns=['timestamp', 'volume'])
        # Merge prices and volumes on timestamp
        df = pd.merge(df_prices, df_volumes, on='timestamp')
        # Convert timestamp to datetime
        df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
        # Sort data by timestamp
        df = df.sort_values('timestamp')
        # Save to CSV
        df.to_csv('market_data.csv', index=False)
        print("Market data collected and saved to market_data.csv")
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")
if __name__ == '__main__':
    fetch_market_data()

Explanation of the Code

  • API Endpoint: Uses the CoinGecko API to fetch historical market data.

  • Parameters:

    • coin_id: The cryptocurrency identifier (e.g., 'bitcoin').

    • vs_currency: The fiat currency to compare against (e.g., 'usd').

    • days: The number of days of data to retrieve.

  • Data Retrieved:

    • Prices: Historical prices at different timestamps.

    • Volumes: Trading volumes at different timestamps.

  • Data Processing:

    • Merges price and volume data.

    • Converts timestamps to human-readable datetime.

    • Sorts data chronologically.

  • Error Handling:

    • Catches HTTP errors and general exceptions.

  • Output: Saves the processed data to market_data.csv.

Execute the following command to collect the market data:

python data_collector.py

Expected Output:

Run the Data Collector

market_data.csv file

Run the Data Collector

Note: The number of data points may vary depending on the API's data granularity.

Step 2. Build an AI Model

With the data collected, we'll build an AI model to predict future Bitcoin prices. In your project directory, create a file named ai_model.py and copy the below code

import pandas as pd

from sklearn.linear_model import LinearRegression

import sys

import json

import warning

warnings.filterwarnings("ignore")

# Load historical market data

data = pd.read_csv('market_data.csv')

# Feature Engineering: Use previous price as a feature

data['prev_price'] = data['price'].shift(1)

data = data.dropna()

# Prepare the data

X = data[['prev_price']]

y = data['price']

# Train the model

model = LinearRegression()

model.fit(X, y)

# Make a prediction

# Accept the latest price as a command-line argument

if len(sys.argv) > 1:

    latest_price = float(sys.argv[1])

else:

    latest_price = X.iloc[-1]['prev_price']  # Use the last known price

prediction = model.predict([[latest_price]])

# Output the prediction in JSON format

print(json.dumps({'prediction': prediction[0]}))

Explanation of the Code

  • Data Loading: Reads the market_data.csv file.

  • Preprocessing:

    • Feature Engineering: Creates features from previous price and volume.

    • Handles Missing Values: Drops rows with NaN values resulting from the shift operation.

  • Model Training:

    • Uses LinearRegression from scikit-learn.

  • Prediction:

    • Accepts the latest price and volume as inputs.

    • Predicts the future price.

  • Command-Line Arguments:

    • latest_price: Latest known price (passed from Node.js script).

    • latest_volume: Latest known volume (passed from Node.js script).

  • Output: Prints the prediction in JSON format.
    Panda Prediction Output

Step 3. Set Up the Node.js Server

We'll set up an Express server to handle API requests and integrate the AI model. In your project directory, create a file named index.js:

const express = require('express');

const axios = require('axios');

const { execFile } = require('child_process');

const path = require('path');

const app = express();

app.use(express.json());

function getAIPrediction(latestPrice) {

  return new Promise((resolve, reject) => {

    execFile('python', ['ai_model.py', latestPrice], { cwd: __dirname }, (error, stdout, stderr) => {

      if (error) {

        console.error('Error executing Python script:', error);

        reject(error);

      } else if (stderr) {

        console.error('Python script error output:', stderr);

        reject(stderr);

      } else {

        try {

          console.log('Python script output:', stdout);

          const result = JSON.parse(stdout);

          resolve(result.prediction);

        } catch (error) {

          console.error('Error parsing Python script output:', error);

          reject(error);

        }

      }

    });

  });

}

// API Endpoint to Predict Price

app.get('/predict_price', async (req, res) => {

  try {

    // Fetch latest price

    const response = await axios.get('https://api.coingecko.com/api/v3/simple/price', {

      params: {

        ids: 'bitcoin',

        vs_currencies: 'usd',

      },

    });

    const latestPrice = response.data.bitcoin.usd;

    // Get AI prediction

    const predictedPrice = await getAIPrediction(latestPrice);

    res.json({

      latest_price: {

        value: latestPrice,

        currency: 'USD',

      },

      predicted_price: {

        value: predictedPrice,

        currency: 'USD',

      },

    });

  } catch (error) {

    console.error('Error predicting price:', error);

    res.status(500).json({ error: error.message });

  }

});

// Start server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

  console.log(`Server is running on port ${PORT}`);

});

// Initial Actions

(async () => {

  try {

    // Fetch latest price

    const response = await axios.get('https://api.coingecko.com/api/v3/simple/price', {

      params: {

        ids: 'bitcoin',

        vs_currencies: 'usd',

      },

    });

    const latestPrice = response.data.bitcoin.usd;

    console.log(`Latest Bitcoin Price: $${latestPrice}`);

    // Get AI prediction

    const predictedPrice = await getAIPrediction(latestPrice);

    console.log(`AI Predicted Price: $${predictedPrice.toFixed(2)} USD`);

    // Simple trading strategy

    if (predictedPrice > latestPrice * 1.01) {

      console.log('Prediction suggests price will increase. Consider buying.');

    } else if (predictedPrice < latestPrice * 0.99) {

      console.log('Prediction suggests price will decrease. Consider selling.');

    } else {

      console.log('Prediction suggests price will remain stable. Hold position.');

    }

  } catch (error) {

    console.error('Error during AI processing:', error);

  }

})();

Explanation of the Code

  • Data Fetching:

    • Retrieves the latest price and volume for Bitcoin.

    • Uses axios to make concurrent API calls to CoinGecko.

  • AI Prediction Integration:

    • Uses child_process.execFile to run the Python script.

    • Passes latestPrice and latestVolume as arguments.

    • Parses the JSON output from the Python script.

  • API Endpoint:

    • /predict_price: Returns the latest price, volume, and AI-predicted price.

  • Initial Actions:

    • Fetches data upon starting the server.

    • Prints predictions and trading suggestions to the console.

  • Error Handling:

    • Logs errors and returns appropriate HTTP responses.

Important Note: If you have multiple Python versions installed, use 'python3' instead of 'python' in execFile. On Windows, you may need to specify the full path to the Python executable.

Step 4: Run the Application

Ensure all Node.js dependencies and required modules are installed:

npm install

npm install

Start the Server

node index.js

Expected Output:

Start Node Server

Step 5. Test the AI Prediction Endpoint

Using cURL

curl http://localhost:3000/predict_price

Expected Output

{
  "latest_price": {
    "value": XXXXX,
    "currency": "USD"
  },
  "predicted_price": {
    "value": XXXXX,
    "currency": "USD"
  }
}

Test the AI Prediction Endpoint

Note: Actual values will vary based on current market data.


Conclusion

If you've been following along, you've built a simple AI crypto price prediction model using historical market data and integrated it into a web server. From here, you can take it further by training it with advanced AI models, expanding support for multiple cryptocurrencies, and refining the interface for a better user experience. If you enjoyed this article, be sure to check out our article on building an AI assistant to track profit and loss

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 6
Roxait
Roxait
With 18 years of pioneering experience in the crypto space, Roxait excels in technical collaborations to develop cutting-edge decentralized solutions. Our commitment to innovation and expertise in blockchain technology has made us a trusted partner in driving the future of decentralized systems. Follow the author on Twitter @roxaittech

Related Articles

Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Log in
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
or
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Sign up
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
or
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
Didn't receive confirmation instructions?
Resend confirmation instructions
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
coingecko
Continue in app
Track prices in real-time
Open App