Downloading historical cryptocurrency data can be achieved by using various APIs that provide market information. One popular choice for accessing such data is the CoinGecko API, which is free and does not necessarily require API keys for low-frequency requests.
Here's a simple Python script that demonstrates how to use the pycoingecko library to fetch historical data. First, you need to install the package, if you haven't done so:
pip install pycoingecko
Python Script for Historical Cryptocurrency Data
from pycoingecko import CoinGeckoAPI
import pandas as pd
import datetime
cg = CoinGeckoAPI()
def fetch_historical_data(coin_id, vs_currency='usd', days='max', interval='daily'):
"""
Fetch historical data for a given coin.
:param coin_id: CoinGecko ID for the coin, e.g., 'bitcoin'.
:param vs_currency: The currency to compare against, e.g., 'usd'.
:param days: The number of days to fetch ('1', '14', '30', 'max', etc.)
:param interval: The data interval. Valid values: 'minutely', 'hourly', 'daily'.
:return: DataFrame with historical data.
"""
data = cg.get_coin_market_chart_by_id(id=coin_id, vs_currency=vs_currency, days=days, interval=interval)
df_prices = pd.DataFrame(data['prices'], columns=['timestamp', 'price'])
df_volumes = pd.DataFrame(data['total_volumes'], columns=['timestamp', 'volume'])
df = pd.merge(df_prices, df_volumes, how='inner', on='timestamp')
df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
df.drop('timestamp', axis=1, inplace=True)
df.set_index('date', inplace=True)
return df
# Example usage:
coin_id = 'bitcoin' # CoinGecko ID of the cryptocurrency
vs_currency = 'usd' # The currency to compare against
# Adjust the 'days' and 'interval' parameters based on your requirements:
# For 1h data, you might fetch daily and then resample
# Note: The interval might be limited to 'daily' depending on the API capabilities.
df_bitcoin_daily = fetch_historical_data(coin_id, vs_currency, days='30', interval='daily') # Daily for the last 30 days
print(df_bitcoin_daily.head())
# Resampling (for illustration, even though CoinGecko might not provide hourly data directly through this method):
# Hourly
df_hourly = df_bitcoin_daily.resample('H').ffill() # Forward fill to illustrate resampling
print(df_hourly.head())
# Note: For other intervals such as 1h, 4h, 1w, and monthly which may not directly be supported
# via the 'interval' argument, you may need to do manual resampling or aggregation.
This example demonstrates how to fetch daily data and includes a simple method for resampling to demonstrate how you might achieve different timeframes. However, for actual 1h, 4h, and so on, please review the API's documentation or consider other APIs if higher granularity is needed. Some APIs may require you to manually specify start and end dates to fetch historical minute/hour level data, or you might need to look into aggregating data points.
Remember, fetching data at a very granular level (like 1h or 4h) might not be directly available for 'max' days because of the vast amount of data. You might need to fetch such data in chunks or select a narrower date range.