give me code to download bitcoin dominance historical data to a csv file
- User
give me code to download bitcoin dominance historical data to a csv file
- Assistant
To download Bitcoin dominance historical data, you need to access an API that provides such information. CoinGecko API is a popular choice that offers cryptocurrency data, including Bitcoin dominance, without the need for an API key for small requests.
Below is a Python code snippet that uses the
requestslibrary to access the CoinGecko API and fetch the historical data for Bitcoin dominance. It then saves the data to a CSV file namedbitcoin_dominance.csv. This assumes that we're dealing with daily historical data for simplicity.Make sure to install the
requestsandpandaslibraries if you haven't already:pip install requests pandasHere is the code:
import requests import pandas as pd from datetime import datetime def fetch_bitcoin_dominance(start_date, end_date): url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range" params = { 'vs_currency': 'usd', 'from': start_date.timestamp(), 'to': end_date.timestamp(), } response = requests.get(url, params=params) response_json = response.json() # Extract the 'market_caps' property, which represents market cap data # The Bitcoin dominance can be calculated from the market cap market_caps = response_json.get('market_caps', []) # Convert to a DataFrame df = pd.DataFrame(market_caps, columns=['timestamp', 'market_cap']) # Convert timestamp to datetime df['date'] = pd.to_datetime(df['timestamp'], unit='ms') # We will not calculate actual Bitcoin dominance, but rather just save the market cap. # You can adjust the logic to find the exact dominance percentage if needed. df = df.drop('timestamp', axis=1) return df start_date = datetime(2021, 1, 1) # For example, get data starting from January 1, 2021 end_date = datetime.now() # Up to the current date bitcoin_dominance_df = fetch_bitcoin_dominance(start_date, end_date) # Save to CSV bitcoin_dominance_df.to_csv('bitcoin_dominance.csv', index=False)Please note that the CoinGecko API does not directly provide Bitcoin dominance data. Instead, it provides Bitcoin's market cap, from which dominance could be calculated if you have the total market cap of all cryptocurrencies. You'd need to fetch that data and calculate the percentage dominance by dividing Bitcoin's market cap by the total market cap.
The above code snippet may require adjustment depending on CoinGecko's API response structure at the time you run it, and if you choose to calculate the actual dominance data, you will need additional data and logic.