This tutorial demonstrates how to download historical OHLC (Open, High, Low, Close) market data from Coinbase using Python. The script leverages the Pandas, requests, and json libraries to fetch and save data as a CSV file.
Step-by-Step Guide
Prerequisites
- Python 3.x installed
Required libraries:
pip install pandas requests
Python Script
import pandas as pd
import requests
import json
def download_coinbase_data(pair, filename):
url = f"https://api.pro.coinbase.com/products/{pair}/candles?granularity=86400"
response = requests.get(url)
data = json.loads(response.text)
df = pd.DataFrame(data, columns=["time", "low", "high", "open", "close", "volume"])
df['time'] = pd.to_datetime(df['time'], unit='s')
df.to_csv(filename, index=False)
print(f"Data saved to {filename}")
# Example usage:
download_coinbase_data("BTC-USD", "Coinbase_BTCUSD_dailydata.csv")Key Features
- Customizable: Adjust the
pairparameter (e.g.,ETH-USD,LTC-USD) andgranularity(e.g.,3600for hourly data). - Output: Generates a CSV file named
Coinbase_[PAIR]_dailydata.csv.
Enhancements
- Database Integration: Modify the script to store data in SQLite/PostgreSQL.
- Automation: Schedule daily downloads using
cronor Windows Task Scheduler. - Error Handling: Add retries for API rate limits or network issues.
👉 Explore advanced crypto data tools for institutional-grade analytics.
FAQs
1. Is the Coinbase API free to use?
Yes, but rate limits apply. Check Coinbase’s API documentation for details.
2. Can I download minute-level data?
Absolutely! Adjust the granularity parameter (e.g., 60 for 1-minute candles).
3. How do I handle API authentication?
This example uses public endpoints. For private data, include API keys with proper encryption.
Best Practices
- Data Validation: Verify timestamps and missing values.
- Legal Compliance: Adhere to Coinbase’s Market Data Terms.
👉 Optimize your trading strategy with real-time market insights.
Final Notes
This script is for educational purposes. Cryptocurrency trading involves risks—only invest capital you can afford to lose.
Disclaimer: This content is not financial advice. Past performance does not guarantee future results.