Cryptocurrency analysis involves tracking price trends, historical data, market sentiment, and predicting future movements using Python. Libraries such as pandas, NumPy, matplotlib, yfinance, and ccxt are commonly used.
Key Topics Covered
✔ Fetching real-time crypto prices
✔ Analyzing historical cryptocurrency data
✔ Visualizing crypto price trends
✔ Calculating moving averages for trend analysis
✔ Sentiment analysis for crypto news
✔ Predicting cryptocurrency prices with Machine Learning
1. Installing Required Libraries
pip install requests pandas matplotlib seaborn yfinance ccxt nltk scikit-learn
2. Fetching Real-Time Cryptocurrency Prices
Using the CoinGecko API to get the latest crypto prices
import requests
# API URL for Bitcoin price
url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd"
# Fetch data
response = requests.get(url).json()
print("Bitcoin Price:", response["bitcoin"]["usd"])
print("Ethereum Price:", response["ethereum"]["usd"])
✔ Used for real-time crypto tracking
3. Fetching Historical Data Using yfinance
Get historical price data for Bitcoin
import yfinance as yf
# Download historical data for Bitcoin
btc = yf.download("BTC-USD", start="2023-01-01", end="2024-01-01")
print(btc.head())
✔ Essential for backtesting trading strategies
4. Visualizing Cryptocurrency Price Trends
Plot Bitcoin’s price movement over time
import matplotlib.pyplot as plt
# Plot Bitcoin price
plt.figure(figsize=(10, 5))
plt.plot(btc['Close'], label="Bitcoin Closing Price", color='orange')
plt.title("Bitcoin Price Trend")
plt.xlabel("Date")
plt.ylabel("Price (USD)")
plt.legend()
plt.show()
✔ Helps in technical analysis
5. Calculating Moving Averages
Moving Averages help identify trends
import pandas as pd
# Calculate 50-day and 200-day moving averages
btc['50_MA'] = btc['Close'].rolling(window=50).mean()
btc['200_MA'] = btc['Close'].rolling(window=200).mean()
# Plot moving averages
plt.figure(figsize=(10, 5))
plt.plot(btc['Close'], label="Bitcoin Price", color='black')
plt.plot(btc['50_MA'], label="50-Day MA", color='blue')
plt.plot(btc['200_MA'], label="200-Day MA", color='red')
plt.legend()
plt.title("Bitcoin Moving Averages")
plt.show()
✔ Used in trading strategies
6. Cryptocurrency Sentiment Analysis
Extract crypto news & analyze sentiment using NLTK
from textblob import TextBlob
news = ["Bitcoin hits new all-time high!", "Ethereum crashes 20% in a day!", "Crypto market is booming!"]
# Analyze sentiment
for article in news:
sentiment = TextBlob(article).sentiment.polarity
print(f"News: {article} | Sentiment Score: {sentiment}")
✔ Used for sentiment-driven trading strategies
7. Predicting Crypto Prices with Machine Learning
Using Linear Regression to predict Bitcoin prices
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Prepare data
btc['Next_Day_Price'] = btc['Close'].shift(-1)
btc.dropna(inplace=True)
X = btc[['Close']]
y = btc['Next_Day_Price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict next day's price
predicted_price = model.predict([[btc['Close'].iloc[-1]]])
print(f"Predicted Bitcoin Price: ${predicted_price[0]:.2f}")
✔ Basic ML model for price prediction
8. Fetching Crypto Market Data Using ccxt
Extract Bitcoin price from Binance Exchange
import ccxt
# Connect to Binance
binance = ccxt.binance()
# Fetch market data
btc_ticker = binance.fetch_ticker('BTC/USDT')
print(f"Bitcoin Price on Binance: {btc_ticker['last']}")
✔ Essential for trading bots