|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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庫中,因此您不需要單獨安裝它。catetime: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
- 聯準會維持利率的決定,加上中東衝突,影響了比特幣的價格。分析近期趨勢和市場反應。
-
-
-
-
-
-
































