How to get Bitcoin prices in Python for Beginners

1 min

You might want to analyze crypto prices.

In order to do some portfolio analysis or other nice things.

Here is the simplest way to retrieve data from the Coingecko free API.

The documentation is available here

The cleanest

import requests

# We define the coingecko id of the crypto we want to fetch
coin_id = "bitcoin"

# We create the url that we will have to fetch
url_ohlc_coin = f"https://api.coingecko.com/api/v3/coins/{coin_id}/ohlc" 

# We set up the additional parameters to be 
# passed during the https call
query_parameters = {
    "vs_currency" : "usd",
    "days" : "14"
}

# We perform the https call against the api and get back a response object
response = requests.get(url_ohlc_coin, params=query_parameters)

# We parse the json data into a btc_prices object
btc_prices = response.json()

# We pass this dict to the pandas dataframe to create a dataframe
df_btc_prices = pd.DataFrame(btc_prices)
The cleanest way of doing it

The simplest

For the quick and dirty aficionados out there is a simpler solution. Thanks to the pandas library.

df_btc_prices = pd.read_json("https://api.coingecko.com/api/v3/coins/bitcoin/ohlc?vs_currency=usd&days=14")
The shortest way to do it

As you can see the dates are still considered as int64.

In order to format it into a human readable format you can use the pandas.to_datetime function.

I wrote an article with the code available here

How to format dates with Pandas
How to format dates with Pandas. A simple way is to use the pandas.to_datetime() method. Here are two use cases.