Analysing Crypto Prices with Python

Analysing Crypto Prices with Python

The crypto-world is one of many interesting things I’ve discovered this year, and it is, by far, the most exciting one. When I say crypto-world I mean everything it involves: uses of blockchain, on-chain analysis, cryptocurrencies markets and applications, and beyond.

In this article I don't plan to write about all of that, but if you are interested on this subject feel free to reach me and we chat about it! 😉

Well, let’s start by getting the data!

First, It's important to think how to pull the data. In Python, there are many different options when comes to finance data, the most commons are: Binance's API (for crypto), Yahoo Finance (for stocks and financial data), or InvestPy (for both). In this analysis, I will use InvestPy.

!pip install -q investpy        

 After installing my main package, It's time to import pandas and numpy (for data manipulation) and plotly (for data visualization).

# Setting the libraries

import pandas as pd
import investpy as inv
from datetime import date
import numpy as np
import matplotlib.pyplot as plt


import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplotss        

For the timeframe, I selected only data from 2021, but you can choose your own timeframe if you want. And for the cryptocurrencies, I choose Bitcoin and Ethereum.

# Setting the dates for 2021

start_date = '01/01/2021'
end_date   = date.today().strftime("%d/%m/%Y")

 
# Choosing the coins we will use in this example
coins = ['Bitcoin', 'Ethereum']

crypto_df = pd.DataFrame(columns=coins)


# Then, using the invetPy library we can pull Bitcoin price data

for coin in coins:
    prices = inv.get_crypto_historical_data(coin, 
                                          from_date=start_date, 
                                          to_date=end_date)['Close']
    crypto_df[coin] = asset


crypto_df.reset_index(inplace=True)
        

Visualizing the Prices

After getting the data, it's time to see how the prices changed since the begining of the year. One of the most important things to me when analysing and reporting information is the storytelling and the visualizations.

PS.: This analysis will also be a guide to a great data-viz!! 😉

Normally, when we talk about data visualization in Python the first thing that comes to our mind is MatPlotLib. So, that's why I would like to start using this library.

# Plotting Bitcoin and Ehtereum Prices using MatPlotLib

plt.figure(figsize=(14,8)


plt.plot(prices['Date'], prices['Bitcoin'])
plt.plot(prices['Date'], prices['Ethereum'])
plt.title('Bitcoin and Ethereum Prices in 2021') 
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend(labels=('Bitcoin', 'Ethereum')))        

And that's the result!

Não foi fornecido texto alternativo para esta imagem

Personally, I think it's OK. It's clean, it has the right information, but it looks like a simple output coming from a normal code.

I like things looking great!!

So...let's do some normalization so it's easier to compare both prices and returns. After, I will use one of the greatest data-viz libraries: Plotly!

# Normalizing prices, or comparing the acumulative returns of both cyptocurrencies

prices_norm = prices[coins]/prices[coins].iloc[0]        

Using Plotly:

fig = go.Figure()


# Creating the lines
fig.add_trace(go.Scatter(x=prices['Date'], y=prices_norm['Bitcoin'], mode='lines',
        name='Bitcoin', 
        line=dict(color=colors[0], width=2),
        connectgaps=True
    ))
fig.add_trace(go.Scatter(x=prices['Date'], y=prices_norm['Ethereum'], mode='lines',
        name='Ehtereum', 
        line=dict(color=colors[1], width=2),
        connectgaps=True
    ))


# endpoints
fig.add_trace(go.Scatter(
    x=[prices['Date'].iat[-1]],
    y=[prices_norm['Bitcoin'].iat[-1]],
    mode='markers',
    marker=dict(color=colors[0], size=8),
    showlegend=False
))


fig.add_trace(go.Scatter(
    x=[prices['Date'].iat[-1]],
    y=[prices_norm['Ethereum'].iat[-1]],
    mode='markers',
    marker=dict(color=colors[1], size=8),
    showlegend=False
))



# Removing visual noise
fig.update_layout(
    xaxis=dict(
        showline=True,
        showgrid=False,
        showticklabels=True,
        linecolor='rgb(204, 204, 204)',
        linewidth=2,
        ticks='outside',
        tickfont=dict(
            family='Arial',
            size=12,
            color='rgb(82, 82, 82)',
        ),
    ),
    yaxis=dict(
        showgrid=False,
        zeroline=False,
        showline=False,
        showticklabels=True,
    ),
    autosize=False,
    margin=dict(
        autoexpand=True,
        l=100,
        r=20,
        t=110,
    ),
    showlegend=True,
    plot_bgcolor='white'
)



# Adding labels


annotations = []


annotations.append(dict(xref='paper', x=0.95, y=prices_norm['Ethereum'].iat[-1],
                                  xanchor='left', yanchor='middle',
                                  text='{:.1f}%'.format(prices_norm['Ethereum'].iat[-1] * 100),
                                  font=dict(family='Arial',
                                            size=17),
                                  showarrow=False))


annotations.append(dict(xref='paper', x=0.95, y=prices_norm['Bitcoin'].iat[-1],
                                  xanchor='left', yanchor='middle',
                                  text='{:.1f}%'.format(prices_norm['Bitcoin'].iat[-1] * 100),
                                  font=dict(family='Arial',
                                            size=17),
                                  showarrow=False))


# Adding a nice Title
annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,
                              xanchor='left', yanchor='bottom',
                              text='Bitcoin and Ethereum Acumulative Return in 2021',
                              font=dict(family='Arial',
                                        size=25,
                                        color='rgb(37,37,37)'),
                              showarrow=False))
# And a nice graph legend
annotations.append(dict(xref='paper', yref='paper', x=0.5, y=-0.1,
                              xanchor='center', yanchor='top',
                              text='Made by me, inspired in ' +
                                  'Storytelling with data',
                              font=dict(family='Arial',
                                        size=12,
                                        color='rgb(150,150,150)'),
                              showarrow=False))


fig.update_layout(annotations=annotations)        

It's not simple (nor short) as the MatPlotLib, but the result is definetly worth it!

Não foi fornecido texto alternativo para esta imagem

Now that's really nice!!

Wrapping up!

Personaly, I think data-viz is one the most important skills a data analyst should have. And it's not about good designs or good colors, it's about transmiting clean and usefull information.

In one graph, I can conclude which asset is the least volatile (Bitcoin) and the most profit one (Ethereum). I can also project what could be my returns based on the labels on the right.

This is just the first step to analyse cryptocurrencies. I plan to write some more articles about this topic soon!

Muito bom Sérgio. Muito interessante, são posts assim que mostram como é fantástico transformar dados em conhecimento pra tomada de decisões. Obrigado por compartilhar 🙌

Boa, Sérgio! Baita assunto e baita texto!

Boa, Sérgio! Baita iniciativa, vale apresentar mais no chapter day!

Gostei! Os gráficos estão bem limpos e o assunto é interessante! Mandou bem! 👏

To view or add a comment, sign in

Others also viewed

Explore content categories