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.
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:
- NumPy: A library for numerical computations with support for large, multi-dimensional arrays and matrices.
- Pandas: A library providing data structures and data analysis tools.
- scikit-learn: A machine learning library featuring various algorithms for classification, regression, clustering, and more.
- 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:
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:
market_data.csv file
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.
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
Start the Server
node index.js
Expected Output:
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"
}
}
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.
Subscribe to the CoinGecko Daily Newsletter!