Build a Cryptocurrency Price Tracker in Python
Cryptocurrency markets run 24/7, making automated tracking essential. In this tutorial, we build a crypto price tracker that fetches live prices from the free CoinGecko API, calculates your portfolio value, and sends alerts when prices cross thresholds.
Prerequisites
- ✓Basic Python
- ✓pip installed
- ✓No API key needed (CoinGecko free tier)
Step 1.Install dependencies
requests for API calls, pandas for data, tabulate for pretty terminal output.
pip install requests pandas tabulateStep 2.Fetch live crypto prices
CoinGecko provides free crypto data without authentication. We get price, 24h change, and market cap in one call.
import requests
import pandas as pd
from datetime import datetime
def get_crypto_prices(coins: list, currency: str = "gbp") -> dict:
ids = ",".join(coins)
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
"ids": ids,
"vs_currencies": currency,
"include_24hr_change": "true",
"include_market_cap": "true"
}
r = requests.get(url, params=params, timeout=10)
r.raise_for_status()
return r.json()
coins = ["bitcoin", "ethereum", "solana", "cardano", "polkadot"]
prices = get_crypto_prices(coins)
for coin, data in prices.items():
print(f'{coin}: pounds {data["gbp"]:,.2f} ({data["gbp_24h_change"]:.1f}%)')Step 3.Track your portfolio
Multiply your holdings by live prices to see current portfolio value.
portfolio = {
"bitcoin": 0.5,
"ethereum": 4.0,
"solana": 25.0,
}
total = 0
rows = []
for coin, amount in portfolio.items():
price = prices[coin]["gbp"]
value = amount * price
total += value
rows.append({
"Coin": coin.title(),
"Amount": amount,
"Price": price,
"Value": value,
"Change 24h": f'{prices[coin]["gbp_24h_change"]:.1f}%'
})
df = pd.DataFrame(rows)
print(df.to_string(index=False))
print(f"Total portfolio value: pounds {total:,.2f}")Step 4.Set up price alerts
Define price thresholds and check them against live data. In production, you would send email or push notifications.
ALERTS = {
"bitcoin": {"above": 100000, "below": 40000},
"ethereum": {"above": 5000, "below": 2000},
}
def check_alerts(prices: dict, alerts: dict):
triggered = []
for coin, thresholds in alerts.items():
if coin in prices:
price = prices[coin]["gbp"]
if price > thresholds["above"]:
triggered.append(f"{coin.title()} above {thresholds['above']:,}")
if price < thresholds["below"]:
triggered.append(f"{coin.title()} below {thresholds['below']:,}")
return triggered
alerts = check_alerts(prices, ALERTS)
if alerts:
for a in alerts:
print(f"ALERT: {a}")
else:
print("No alerts triggered")Step 5.Get historical data
Historical data lets you plot trends and calculate moving averages.
def get_price_history(coin: str, days: int = 30) -> pd.DataFrame:
url = f"https://api.coingecko.com/api/v3/coins/{coin}/market_chart"
params = {"vs_currency": "gbp", "days": days}
r = requests.get(url, params=params, timeout=10)
data = r.json()
df = pd.DataFrame(data["prices"], columns=["timestamp", "price"])
df["date"] = pd.to_datetime(df["timestamp"], unit="ms")
return df[["date", "price"]]
btc_history = get_price_history("bitcoin", 30)
print(f'BTC 30-day range: pounds {btc_history["price"].min():,.0f} - pounds {btc_history["price"].max():,.0f}')Expected Output
Coin Amount Price Value Change 24h
Bitcoin 0.5 84250 42125.00 2.3%
Ethereum 4.0 3180 12720.00 1.8%
Solana 25.0 142 3562.50 4.1%
Total portfolio value: pounds 58,407.50Next Steps
- →Add email notifications using smtplib
- →Store historical portfolio values in a database
- →Build a Streamlit dashboard
Recommended Reading
Cryptoassets Investment Book →As an Amazon Associate we may earn from qualifying purchases.