Refactoring Cryptocurrency Data Fetching with Python: A More Efficient Approach to CryptoCompare API
The provided solution is in Python and seems to be fetching historical cryptocurrency data from the CryptoCompare API. Here’s a refactored version with some improvements:
import requests
import pandas as pd
# Define the tickers and the API endpoint
tickers = ['BTC', 'ETH', 'XRP']
url = 'https://min-api.cryptocompare.com/data/histoday'
# Create an empty dictionary to store the data
data_dict = {}
# Loop through each ticker and fetch the data
for ticker in tickers:
# Construct the API request URL
url += '?fsym=' + ticker + '&tsym=USD&limit=600000000000&aggregate=1&e=CCCAGG'
# Send a GET request to the API endpoint
response = requests.get(url)
# If the response was successful, parse the JSON data
if response.status_code == 200:
data = response.json()
# Extract and clean the 'time' column
time_column = pd.to_datetime(data['Data']['time'], unit='s')
data['Time'] = time_column
# Add the cleaned data to the dictionary
data_dict[ticker] = data
else:
print(f"Failed to retrieve data for {ticker}")
# Create a DataFrame from the dictionary values and set 'Time' as the index
dfs = [df.set_index('Time') for df in data_dict.values()]
final_df = pd.concat(dfs, axis=1)
print(final_df.head())
In this version:
- We’ve created a
data_dictdictionary to store the fetched data, which is then used to create a final DataFrame. - The API request URL is constructed using string formatting, and the response status code is checked for success.
- Pandas’
pd.to_datetime()function is used to clean and convert the ’time’ column into a pandas datetime object. - We’ve removed the use of global variables (
globals()['df_' + str(t)]) in favor of encapsulating the data within the script.
Last modified on 2023-08-01