|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
In this blog post, we delve into cryptocurrency price prediction using CoinGecko API and machine learning – the ability to learn patterns from data and make informed predictions.
在这篇博文中,我们使用 CoinGecko API 和机器学习深入研究加密货币价格预测——从数据中学习模式并做出明智预测的能力。

Level of Functionality
We'll first examine the key functionalities of our Python program:
功能级别我们首先检查 Python 程序的关键功能:
- Fetching Data: The program fetches real-time and historical data from the CoinGecko API. This includes the current market data, historical data, and OHLC (Open, High, Low, Close) data for a specific coin.
- Data Processing: The program processes the fetched data to prepare it for the machine learning model. This includes selecting relevant features, scaling the data, and formatting it into the appropriate shape.
- Machine Learning Model: The program uses a Linear Regression model from the Scikit-learn library to learn from the processed data.
- Price Prediction: The program uses the trained model to predict future prices of the selected cryptocurrency.
- Displaying Predictions: The program displays the predicted prices to the user in a simple and intuitive web interface. The user can select a coin and the number of days for which they want to predict prices, and the program will display the predictions in a table.
- User Interaction: The program provides an interactive form for the user to input their preferences. It also handles invalid inputs gracefully by displaying an error message.
- Security Measures: The program ensures the security of sensitive data such as API keys and private keys. It uses secure connections and encrypts sensitive data.
Which machine learning model is best for crypto price prediction?
Among the various machine learning models for crypto price prediction, the Linear Regression model is most optimal for predicting crypto prices because it is simple to understand and implement, and works well with linearly separable data. This model assumes a linear relationship between the input variables (independent variables) and a single output variable (dependent variable).
获取数据:程序从 CoinGecko API 获取实时和历史数据。这包括特定货币的当前市场数据、历史数据和 OHLC(开盘价、最高价、最低价、收盘价)数据。 数据处理:程序处理获取的数据,为机器学习模型做好准备。这包括选择相关特征、缩放数据并将其格式化为适当的形状。机器学习模型:该程序使用 Scikit-learn 库中的线性回归模型来从处理后的数据中学习。价格预测:该程序使用经过训练的模型模型来预测所选加密货币的未来价格。显示预测:该程序在简单直观的 Web 界面中向用户显示预测价格。用户可以选择一种硬币和他们想要预测价格的天数,程序将在表格中显示预测结果。 用户交互:该程序提供了一个交互表单,供用户输入他们的偏好。它还通过显示错误消息来优雅地处理无效输入。安全措施:该程序可确保 API 密钥和私钥等敏感数据的安全。它使用安全连接并加密敏感数据。哪种机器学习模型最适合加密货币价格预测?在用于加密货币价格预测的各种机器学习模型中,线性回归模型最适合预测加密货币价格,因为它易于理解和实现,并且适用于线性可分离数据。该模型假设输入变量(自变量)和单个输出变量(因变量)之间存在线性关系。
When this assumption holds true, Linear Regression can provide a good baseline model for crypto price prediction. However, it’s important to note that crypto prices are influenced by a multitude of factors and may not always exhibit a linear relationship. Therefore, more complex models may sometimes offer better predictive performance. Always remember to validate the assumptions of your model and test its performance using appropriate metrics.
当这个假设成立时,线性回归可以为加密货币价格预测提供良好的基线模型。然而,值得注意的是,加密货币价格受到多种因素的影响,并且可能并不总是表现出线性关系。因此,更复杂的模型有时可能提供更好的预测性能。始终记住验证模型的假设并使用适当的指标测试其性能。
Prerequisites
Before we start, ensure you have the following:
先决条件在我们开始之前,请确保您具备以下条件:
- Python 3.7 or higher installed on your system. Python is a powerful, easy-to-learn programming language that we will use to build our bot.
- A basic understanding of Python programming. While this guide will be detailed, having a basic understanding of Python syntax and programming concepts will be beneficial.
- A text editor: You will need a text editor or an Integrated Development Environment (IDE) to write your code. Some popular options include Visual Studio Code, Sublime Text, and Atom.
- CoinGecko API (Demo): We will be using CoinGecko API to fetch the market chart data for cryptocurrencies. The CoinGecko API has a free Demo plan accessible to all users with a 30 calls/min rate limit and a monthly cap of 10,000 calls. This guide shows you how to generate your Demo API key.
Do note that the API key used in this guide is a placeholder and not a real API key. Please replace it with your own CoinGecko API key for the code to work.
您的系统上安装了 Python 3.7 或更高版本。 Python 是一种功能强大、易于学习的编程语言,我们将用它来构建我们的机器人。对 Python 编程有基本的了解。虽然本指南将很详细,但对 Python 语法和编程概念有基本的了解将是有益的。 文本编辑器:您将需要文本编辑器或集成开发环境 (IDE) 来编写代码。一些流行的选项包括 Visual Studio Code、Sublime Text 和 Atom.CoinGecko API(演示):我们将使用 CoinGecko API 获取加密货币的市场图表数据。 CoinGecko API 有一个免费的演示计划,可供所有用户访问,速率限制为 30 次/分钟,每月上限为 10,000 次调用。本指南向您展示如何生成演示 API 密钥。请注意,本指南中使用的 API 密钥是占位符,而不是真正的 API 密钥。请将其替换为您自己的 CoinGecko API 密钥,代码才能正常工作。
The Python Program
The program is a Flask web application. It starts by importing necessary libraries and initializing a Flask app:
Python 程序该程序是一个 Flask Web 应用程序。首先导入必要的库并初始化 Flask 应用程序:
In this section, we’ll break down the Python code for our Cryptocurrency prediction to understand each part and its role in the overall functionality of the predictor:
在本节中,我们将分解加密货币预测的 Python 代码,以了解每个部分及其在预测器整体功能中的作用:
Importing Necessary Libraries and Modules: The program commences by importing the necessary libraries and modules. These include Flask, a micro web framework written in Python that provides tools, technologies, and possibilities for web application development. It also imports requests, a Python module used for making various types of HTTP requests like GET and POST.
导入必要的库和模块:该程序首先导入必要的库和模块。其中包括 Flask,一个用 Python 编写的微型 Web 框架,为 Web 应用程序开发提供工具、技术和可能性。它还导入 requests,一个用于发出各种类型的 HTTP 请求(如 GET 和 POST)的 Python 模块。
Setting Up Flask Application and API Key: The Flask application is set up, creating an instance of the Flask class which is our WSGI application. The API key for accessing the CoinGecko API, a comprehensive cryptocurrency API that provides access to a wide range of data, is defined.
设置 Flask 应用程序和 API 密钥:设置 Flask 应用程序,创建 Flask 类的实例,这是我们的 WSGI 应用程序。定义了用于访问 CoinGecko API 的 API 密钥,CoinGecko API 是一种全面的加密货币 API,可提供对各种数据的访问。
Defining the Main Route: The main route (/) is defined, which supports both GET and POST methods. When a GET request is made, it fetches the list of available coins from the CoinGecko API. This is done by making a GET request to the CoinGecko API endpoint, which returns a list of all available cryptocurrencies.
定义主路由:定义主路由(/),支持GET和POST两种方法。当发出 GET 请求时,它会从 CoinGecko API 获取可用代币列表。这是通过向 CoinGecko API 端点发出 GET 请求来完成的,该端点返回所有可用加密货币的列表。
Handling POST Requests: If a POST request is made, it gets the coin_id and days from the form data. If the coin_id is valid, it calls the get_market_chart function with coin_id and days as parameters. This function fetches the market chart data for the given coin over the specified number of days.
处理 POST 请求:如果发出 POST 请求,它将从表单数据中获取 coin_id 和天数。如果 coin_id 有效,它将调用 get_market_chart 函数,并以 coin_id 和 days 作为参数。此函数获取给定代币在指定天数内的市场图表数据。
Defining the get_market_chart Function: This function does several things, namely, it calculates the start and end timestamps based on the number of days, fetches the OHLC (Open, High, Low, Close) data for the given coin_id and days, and fetches the historical data for a specific date and the current market data from the CoinGecko API. Next, it prepares the feature matrix X and target vector y for the linear regression model, and scales the data using MinMaxScaler, a feature scaling technique that transforms features by scaling each feature to a given range. Thereafter, it trains the LinearRegression model with X and y and makes predictions using the trained model. It creates a list of dates for the predictions and combines the dates and predictions into a dictionary, and finally, it returns the predictions.
定义 get_market_chart 函数:该函数执行多项操作,即根据天数计算开始和结束时间戳,获取给定 coin_id 和天数的 OHLC(开盘价、最高价、最低价、收盘价)数据,并获取来自 CoinGecko API 的特定日期的历史数据和当前市场数据。接下来,它为线性回归模型准备特征矩阵 X 和目标向量 y,并使用 MinMaxScaler 缩放数据,MinMaxScaler 是一种特征缩放技术,通过将每个特征缩放到给定范围来转换特征。此后,它使用 X 和 y 训练线性回归模型,并使用训练后的模型进行预测。它创建预测的日期列表,并将日期和预测组合到字典中,最后返回预测。
Running the Flask Application: Finally, if the script is run directly, it starts the Flask development server. This server is a built-in, lightweight WSGI web server and provides a quick way to run the application. It is however not recommended for production environments.
运行 Flask 应用程序:最后,如果直接运行脚本,它将启动 Flask 开发服务器。该服务器是一个内置的轻量级 WSGI Web 服务器,提供了一种运行应用程序的快速方法。但不建议在生产环境中使用。
HTML Structure of the Crypto Price Predictons
This application allows users to select a cryptocurrency and a number of days, and then predicts the price of the selected cryptocurrency for the specified number of days. The predictions are displayed in a table format.
加密货币价格预测的 HTML 结构此应用程序允许用户选择一种加密货币和天数,然后预测所选加密货币在指定天数内的价格。预测以表格形式显示。
If there’s an error, such as an invalid coin ID, the application displays an error message. The application uses Jinja templating for dynamic content rendering, which allows it to display different content based on the user’s input and the results of the price prediction.
如果出现错误,例如无效的代币 ID,应用程序会显示错误消息。该应用程序使用 Jinja 模板进行动态内容渲染,这使得它可以根据用户的输入和价格预测的结果显示不同的内容。
Installing Required Python Libraries
Before running the Python program, it’s important to ensure that all the necessary Python libraries are installed. Here’s a brief explanation of the libraries used in the program and how to install them:
安装所需的 Python 库在运行 Python 程序之前,确保安装所有必需的 Python 库非常重要。以下是程序中使用的库以及如何安装它们的简要说明:
- Flask: Flask is a lightweight web application framework. It’s used to create the web interface for the program. Install it with pip:
pip install flask - requests: Requests is a library for making HTTP requests. It’s used to fetch data from the CoinGecko API. Install it with pip:
pip install requests - json: The json module is used to parse the JSON data returned by the CoinGecko API. It’s included in the standard Python library, so you don’t need to install it separately.
- NumPy: NumPy is a library for numerical computing. It’s used to manipulate the data fetched from the API. Install it with pip:
pip install numpy - scikit-learn: Scikit-learn is a library for machine learning. It’s used to create the linear regression model for price prediction. Install it with pip:
pip install scikit-learn - time: The time module is used to work with timestamps. It’s included in the standard Python library, so you don’t need to install it separately.
- datetime: The datetime module is used to work with dates and times. It’s included in the standard Python library, so you don’t need to install it separately.
To install all these libraries at once, you can use the following command:
Flask:Flask 是一个轻量级的 Web 应用程序框架。它用于为程序创建 Web 界面。使用 pip 安装它: pip installflaskrequests:Requests 是一个用于发出 HTTP 请求的库。它用于从 CoinGecko API 获取数据。使用 pip 安装: pip install requestsjson:json 模块用于解析 CoinGecko API 返回的 JSON 数据。它包含在标准Python库中,因此不需要单独安装。 NumPy:NumPy是一个用于数值计算的库。它用于操作从 API 获取的数据。使用 pip 安装它: pip install numpyscikit-learn:Scikit-learn 是一个机器学习库。它用于创建价格预测的线性回归模型。使用 pip 安装它: pip install scikit-learntime:时间模块用于处理时间戳。它包含在标准Python库中,因此您不需要单独安装它。 datetime:datetime模块用于处理日期和时间。它包含在标准Python库中,因此您不需要单独安装它。要一次安装所有这些库,您可以使用以下命令:
pip install flask requests numpy scikit-learn
pip 安装 Flask 请求 numpy scikit-learn
Remember to run these commands in your virtual environment if you’re using one. This will keep your global Python environment clean and manage dependencies for this project separately. If you’re not using a virtual environment, you might need to use pip3 instead of pip and add sudo at the beginning of the commands to install the libraries globally.
如果您使用的是虚拟环境,请记住在虚拟环境中运行这些命令。这将使您的全局 Python 环境保持干净并单独管理该项目的依赖项。如果您不使用虚拟环境,则可能需要使用 pip3 而不是 pip,并在命令开头添加 sudo 来全局安装库。
Testing the Cryptocurrency Prediction
To test the predictor, follow these steps:
测试加密货币预测要测试预测器,请按照以下步骤操作:
Run the Python script in your terminal using python
.py, in this case python predictor.py 使用 python .py 在终端中运行 Python 脚本,在本例中为 python Predictor.py
Open the Web Application: Once the Flask server is running, open a web browser and navigate to the local server’s address (usually http://localhost:5000).
打开 Web 应用程序:Flask 服务器运行后,打开 Web 浏览器并导航到本地服务器的地址(通常为 http://localhost:5000)。
Select a Cryptocurrency: You’ll see a form with a dropdown list of cryptocurrencies. Select the cryptocurrency you’re interested in.
选择一种加密货币:您将看到一个带有加密货币下拉列表的表单。选择您感兴趣的加密货币。
Enter the Number of Days: In the ‘Days’ input field, enter the number of days for which you want to predict prices.
输入天数:在“天数”输入字段中,输入您要预测价格的天数。
Submit the Form: Click the ‘Predict’ button to submit the form. The program will now fetch the relevant data, train the machine learning model, and make predictions.
提交表格:点击“预测”按钮提交表格。该程序现在将获取相关数据,训练机器学习模型并做出预测。
View the Predictions: The predicted prices will be displayed in a table on the webpage. Each row in the table represents one day, with the date and the predicted price.
查看预测:预测价格将显示在网页上的表格中。表中的每一行代表一天,包含日期和预测价格。
Test Different Cryptocurrencies and Timeframes: Try selecting different cryptocurrencies and entering different numbers of days. Check whether the program returns reasonable predictions and handles edge cases well (e.g., a very large number of days).
测试不同的加密货币和时间范围:尝试选择不同的加密货币并输入不同的天数。检查程序是否返回合理的预测并很好地处理边缘情况(例如,大量的天数)。
Remember, the accuracy of the predictions depends on many factors, including the volatility of the cryptocurrency market and the amount of historical data available. Always use such predictions as just one of many tools in your cryptocurrency trading toolkit.
请记住,预测的准确性取决于许多因素,包括加密货币市场的波动性和可用的历史数据量。始终将此类预测用作加密货币交易工具包中的众多工具之一。
Advanced Functionalities and Useful Endpoints
While the guide above covers the basic development of a cryptocurrency price prediction program, CoinGecko API offers a wealth of endpoints that can be used to add more advanced functionalities. Here are some possibilities:
- Historical Snapshots: The ‘/coins/{id}/history’ endpoint provides historical data for a specific date. This could be used to add a feature that allows users to view ‘snapshots’ of the market at different points in the past.
- Anomaly Detection: By using the ‘/coins/markets’ endpoint to fetch real-time market data, you could implement an anomaly detection feature, which alerts users to sudden significant changes in a coin’s price or trading volume.
- Coin Information: The ‘/coins/{id}’ endpoint returns detailed information about a specific coin, from tickers, market data, community data, metadata and more. This could provide users with information on development status, community strength, public interest and more.
- Trending Coins: The ‘/search/trending’ endpoint provides information about trending coins in the last 24 hours. This data point can keep users informed about which coins are currently popular in the market.

Conclusion
In conclusion, this Python program demonstrates the power of machine learning and APIs in predicting cryptocurrency prices. By leveraging the CoinGecko API, the program fetches real-time and historical market data, which is then used to train a linear regression model for Bitcoin price predictions. The program also provides an intuitive web interface for users to interact with, making it a practical tool for anyone interested in cryptocurrencies.
Moreover, the CoinGecko API offers a wealth of endpoints that can be used to add more advanced functionalities to the program, such as sentiment analysis, anomaly detection, historical snapshots, coin information, and trending coins. These functionalities can provide users with deeper insights and a more comprehensive understanding of the cryptocurrency market.
此外,CoinGecko API 提供了丰富的端点,可用于向程序添加更高级的功能,例如情绪分析、异常检测、历史快照、硬币信息和趋势硬币。这些功能可以为用户提供更深入的见解和对加密货币市场更全面的了解。
Testing the program is a crucial step to ensure its accuracy and reliability. By following the step-by-step guide provided, users can test different cryptocurrencies and timeframes, and check the program’s performance under various scenarios.
测试程序是确保其准确性和可靠性的关键一步。通过遵循提供的分步指南,用户可以测试不同的加密货币和时间范围,并检查程序在各种场景下的性能。
Remember, while such a program can provide valuable predictions and insights, it should be used as just one of many tools in your cryptocurrency trading toolkit. Always consider multiple factors, sources of information and do your own research when making trading decisions. Happy coding and trading!
请记住,虽然这样的程序可以提供有价值的预测和见解,但它应该仅用作加密货币交易工具包中的众多工具之一。在做出交易决策时,始终考虑多种因素、信息来源并进行自己的研究。快乐编码和交易!
If you found this tutorial useful, check out other similar API Guides.
如果您发现本教程有用,请查看其他类似的 API 指南。
Rollend is a Microsoft Certified Cloud Architect with 16 years of experience. He is the author of the book “Automate Your Life: Streamline Your Daily Tasks with Python: 30 Powerful Ways to Streamline Your Daily Tasks with Python”.Follow the author on Twitter @RollendXavier
CoinGecko 的内容编辑指南CoinGecko 的内容旨在揭开加密货币行业的神秘面纱。虽然您看到的某些帖子可能受到赞助,但我们努力维护编辑质量和诚信的最高标准,并且不会发布任何未经我们编辑审查的内容。了解更多告诉我们您有多喜欢这篇文章!Rollend XavierRollend 是微软认证云架构师,拥有 16 年经验。他是《Automate Your Life: Streamline Your Daily Tasks with Python: 30 Powerful Ways to Streamline Your Daily Tasks with Python》一书的作者。在 Twitter 上关注作者 @RollendXavier
阅读罗伦德·泽维尔的更多内容
免责声明:info@kdj.com
所提供的信息并非交易建议。根据本文提供的信息进行的任何投资,kdj.com不承担任何责任。加密货币具有高波动性,强烈建议您深入研究后,谨慎投资!
如您认为本网站上使用的内容侵犯了您的版权,请立即联系我们(info@kdj.com),我们将及时删除。
-
- 比特币、eCash 分叉和空投动态:深入探讨加密货币的最新争议
- 2026-05-03 00:52:02
- 探索最近的 eCash 分叉、其作为高风险空投的分类,以及对比特币和加密生态系统的更广泛影响。
-
-
- 美联储维持利率稳定,地缘政治紧张局势引发比特币价格下跌
- 2026-05-01 04:04:38
- 美联储维持利率的决定,加上中东冲突,影响了比特币的价格。分析近期趋势和市场反应。
-
-
-
-
-
-

































