Analyzing a 30-day Bitcoin Dollar chart with Python and the CryptoCompare API

Hello everyone interested in analyzing cryptocurrency data! Today I'm going to show you how to use Python and CryptoCompare APIto create a 30-day Bitcoin Dollar chart.

btc pic
(Illustration of AI-generated bitcoin)

The Bitcoin price is one of the most important indicators in the cryptocurrency market, with a huge impact on investors. In this post, I'll show you how to get the data and how to visualize it in two parts.

What is a Bitcoin Dollar Chart?

The Bitcoin Dollar chart is a visual representation of the price change of Bitcoin in United States dollars (USD) over a specific period of time. From this chart, we can get the following information

  1. Price trends: It's easy to figure out whether the price of Bitcoin is rising or falling.
  2. Volatility: You can see when there has been a dramatic change in price.
  3. Investment decisions: It can help you make future investment decisions based on historical price data.

Let's start by looking at how to get 30 days of Bitcoin dollar price data using Python.

1. Get 30 days of Bitcoin dollar price data with Python

First, let's install and import the libraries we need.

import requests
import pandas as pd
from datetime import datetime, timedelta

Require # CryptoCompare API key
API_KEY = 'Enter your API key here'

Set the # 30-day time period
end_date = int(datetime.now().timestamp())
start_date = int((datetime.now() - timedelta(days=30)).timestamp())

url = f"https://min-api.cryptocompare.com/data/v2/histoday"

params = {
    'fsym': 'BTC',
    'tsym': 'USD',
    'limit': 30,
    'api_key': API_KEY
}

try:
    response = requests.get(url, params=params)
    data = response.json()['Data']['Data']

    Create a # data frame
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['time'], unit='s')

    print(df.head()) Check the # data

except Exception as e:
    print(f"error: {e}")

Code commentary

  1. import requests, import pandas as pd: Import the required libraries.
  2. API_KEYEnter your CryptoCompare API key. You'll need to get it after signing up for free (I'll write a separate post for those who are struggling).
  3. end_dateand start_dateSets a timestamp from 30 days ago to the present, relative to the current date.
  4. url: Sets the endpoint URL for the CryptoCompare API.
  5. paramsSets the parameters to request.
  6. response = requests.get(url, params=params): Send a GET request to the API.
  7. data = response.json()['Data']['Data']: Extract the data you need from the JSON response.
  8. df = pd.DataFrame(data): Convert data to a dataframe.
  9. df['date']: Convert timestamp to date format.

2. Draw a 30-day Bitcoin Dollar chart

Now let's visualize a Bitcoin dollar chart using the imported data.

import matplotlib.pyplot as plt

Visualize #
plt.figure(figsize=(15, 7))
plt.plot(df['date'], df['close'], color='blue', linewidth=2, marker='o')

plt.title('Bitcoin Price Over Last 30 Days (USD)', fontsize=16)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Price (USD)', fontsize=12)

Formatting the # x-axis date
plt.gcf().autofmt_xdate()

plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()

# Show the price at each point
for x, y in zip(df['date'], df['close']):
    plt.text(x, y, f'${y:,.0f}', fontsize=9,
             verticalalignment='bottom',
             horizontalalignment='center')

plt.savefig('bitcoin_price_30days.png', dpi=300)
plt.show()
비트코인 달러 차트
(Bitcoin Dollar Chart Plotted in Python)

Code commentary

  1. import matplotlib.pyplot as plt: Import the matplotlib library for data visualization.
  2. plt.figure(figsize=(15, 7)): Sets the size of the graph.
  3. plt.plot(...): Represent the price of Bitcoin as a line graph.
  4. plt.title(...), plt.xlabel(...), plt.ylabel(...): Set the graph title and axis labels.
  5. plt.gcf().autofmt_xdate(): Automatically adjusts the x-axis date format.
  6. plt.grid(...): Add a grid to the graph to make it more readable.
  7. Each data point is labeled with the price for that day to make the information clearer.

Finalize

So there you have it, how to use Python coding and the CryptoCompare API to fetch 30 days of data and visualize it in a Bitcoin Dollar chart. These data analysis skills can be very helpful in making crypto investment decisions.

What do you think? Have you tried running this code? What insights did you get from analyzing 30 days of data? This visualization is also possible with non-Python coding in R. Check out another Tracking the Bitcoin Dollar Price Dance in R: Price Trend Analysis for Beginners Check it out in the post!

Similar Posts