-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCoinMarketCap_functions.py
More file actions
173 lines (128 loc) · 5.57 KB
/
CoinMarketCap_functions.py
File metadata and controls
173 lines (128 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Daniele Bianchi, d.bianchi@qmul.ac.uk, whitesphd.com
"""
from datetime import datetime, timedelta
import requests
import json
import pandas as pd
import time
def fetch_historical_data(crypto_id: int, api_key: str, start_date: str, end_date: str, fiat: str, interval: str):
url = 'https://pro-api.coinmarketcap.com/v2/cryptocurrency/ohlcv/historical'
# Convert datetime objects to timestamps
start = int(start_date.timestamp())
end = int(end_date.timestamp())
parameters = {
'id': crypto_id,
'time_start': start,
'time_end': end,
'convert': fiat,
'count': 10000, # Check if 'count' is a valid parameter for your API endpoint
'interval': interval,
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
response = requests.get(url, headers=headers, params=parameters)
if response.status_code == 200:
data = response.json().get('data', {})
name = data.get('name')
symbol = data.get('symbol')
quotes = data.get('quotes', [])
df_results = pd.DataFrame() # Initialize an empty DataFrame
for item in quotes: # Iterate through each item in the data list
# Flatten the nested structure and exclude specific keys
flat_data = {**item['quote']['USD']}
flat_data['timestamp'] = item['time_close'] # Assigning the timestamp for reference
flat_data['name'] = name # Add the name to each row
flat_data['symbol'] = symbol # Add the symbol to each row
# Convert the flattened dictionary into a DataFrame and append it to the results
df = pd.DataFrame([flat_data]) # Convert dictionary into a DataFrame
df_results = df_results.append(df, ignore_index=True)
return df_results
else:
print(f'Failed to retrieve data for ID {crypto_id}: Error code {response.status_code}')
return None
def fetch_crypto_metadata(api_key: str, crypto_id: int):
url = f'https://pro-api.coinmarketcap.com/v2/cryptocurrency/info'
parameters = {
'id': crypto_id,
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
response = requests.get(url, headers=headers, params=parameters)
# Check if response is successful
if response.status_code == 200:
data = response.json().get('data', {}).get(str(crypto_id))
# Check if data was found
if data:
# Flatten urls by creating new keys
for key, value in data['urls'].items():
# Only add if the list is not empty
data[f'url_{key}'] = ', '.join(value) if value else ''
# Remove the original 'urls' field as it's now flattened
del data['urls']
# Convert the modified dictionary into a DataFrame
df = pd.DataFrame([data]) # Pass the dictionary as a list
return df
else:
print(f"No data found for cryptocurrency with ID {crypto_id}")
return None
else:
print(f"Failed to retrieve data: Error code {response.status_code}")
return None
def fetch_historical_global_metrics(api_key: str, start_date: str, end_date: str, interval: str):
url = 'https://pro-api.coinmarketcap.com/v2/global-metrics/quotes/historical' # Hypothetical endpoint
# Convert datetime objects to timestamps
start = int(start_date.timestamp())
end = int(end_date.timestamp())
parameters = {
'time_start': start, # Format: 'YYYY-MM-DD'
'time_end': end, # Format: 'YYYY-MM-DD'
'interval': interval, # e.g., 'daily'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
response = requests.get(url, headers=headers, params=parameters)
if response.status_code == 200:
data = response.json().get('data', {}).get('quotes', [])
df_results = pd.DataFrame() # Initialize an empty DataFrame
for quote in data: # Fixed iteration over 'data'
# Flatten the nested 'quote' dictionary
flat_data = {
**quote,
**quote['quote']['USD'] # Merge the inner USD dictionary into the main dictionary
}
del flat_data['quote'] # Remove the original nested 'quote' field
# Convert the flattened dictionary into a DataFrame and append it to the results
df = pd.DataFrame([flat_data]) # Convert dictionary into a DataFrame
df_results = df_results.append(df, ignore_index=True)
return df_results
else:
print(f"Failed to fetch data: {response.status_code}")
return None
def fetch_coin_category_info(api_key: str, category_id: str):
url = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/category' # Hypothetical endpoint
headers = {
'X-CMC_PRO_API_KEY': api_key,
'Accepts': 'application/json'
}
parameters = {
'id': category_id,
'limit': 1000,
}
response = requests.get(url, headers=headers, params=parameters)
if response.status_code == 200:
# Assuming the data structure is consistent with CoinMarketCap's standards
category_data = response.json().get('data', {})
return category_data
else:
print(f"Failed to fetch data for category {category_id}: {response.status_code}")
return {}