1. Bitcoin. Cryptocurrencies. So hot right now.

Since the launch of Bitcoin in 2008, hundreds of similar projects based on the blockchain technology have emerged. We call these cryptocurrencies (also coins or cryptos in the Internet slang). Some are extremely valuable nowadays, and others may have the potential to become extremely valuable in the future1. In fact, on the 6th of December of 2017, Bitcoin has a market capitalization above $200 billion.


The astonishing increase of Bitcoin market capitalization in 2017.

*1 WARNING: The cryptocurrency market is exceptionally volatile and any money you put in might disappear into thin air. Cryptocurrencies mentioned here might be scams similar to Ponzi Schemes or have many other issues (overvaluation, technical, etc.). Please do not mistake this for investment advice. *

That said, let's get to business. As a first task, we will load the current data from the coinmarketcap API and display it in the output.

import requests
# Importing pandas
import pandas as pd

# Importing matplotlib and setting aesthetics for plotting later.
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg' 
plt.style.use('fivethirtyeight')

# Getting the data
data = requests.get("https://api.coinmarketcap.com/v1/ticker/")
# Reading in current data from coinmarketcap.com
current = pd.DataFrame(data.json())

# Printing out the first few lines
# ... YOUR CODE FOR TASK 1 ...
current.head()
24h_volume_usd available_supply id last_updated market_cap_usd max_supply name percent_change_1h percent_change_24h percent_change_7d price_btc price_usd rank symbol total_supply
0 21766312573.7 18180900.0 bitcoin 1579958614 151521615980 21000000.0 Bitcoin 0.03 -1.13 -6.29 1.0 8334.10975142 1 BTC 18180900.0
1 9129485280.35 109423844.0 ethereum 1579958601 17547851782.0 None Ethereum 0.37 -0.59 -6.89 0.01924797 160.365886634 2 ETH 109423844.0
2 1481529835.06 43675903665.0 xrp 1579958645 9612916998.0 100000000000 XRP 0.23 -1.39 -7.94 0.00002642 0.2200965794 3 XRP 99991104396.0
3 2448790511.0 18242200.0 bitcoin-cash 1579958648 5650036276.0 21000000.0 Bitcoin Cash -0.01 -3.55 -13.5 0.03717499 309.723403741 4 BCH 18242200.0
4 2131454629.84 18222577.0 bitcoin-sv 1579958651 4722454400.0 21000000.0 Bitcoin SV -1.01 -6.5 -0.88 0.03110533 259.154035229 5 BSV 18222577.0

2. Full dataset, filtering, and reproducibility

The previous API call returns only the first 100 coins, and we want to explore as many coins as possible. Moreover, we can't produce reproducible analysis with live online data. To solve these problems, we will load a CSV we conveniently saved on the 6th of December of 2017 using the API call https://api.coinmarketcap.com/v1/ticker/?limit=0 named datasets/coinmarketcap_06122017.csv.

dec6 = pd.read_csv('datasets/coinmarketcap_06122017.csv')

# Selecting the 'id' and the 'market_cap_usd' columns
market_cap_raw = dec6[['id', 'market_cap_usd']]

# Counting the number of values
# ... YOUR CODE FOR TASK 2 ...
print(market_cap_raw.count())
id                1326
market_cap_usd    1031
dtype: int64

3. Discard the cryptocurrencies without a market capitalization

Why do the count() for id and market_cap_usd differ above? It is because some cryptocurrencies listed in coinmarketcap.com have no known market capitalization, this is represented by NaN in the data, and NaNs are not counted by count(). These cryptocurrencies are of little interest to us in this analysis, so they are safe to remove.

cap = market_cap_raw.query('market_cap_usd > 0')

# Counting the number of values again
# ... YOUR CODE FOR TASK 3 ...
print(cap.count())
id                1031
market_cap_usd    1031
dtype: int64

4. How big is Bitcoin compared with the rest of the cryptocurrencies?

At the time of writing, Bitcoin is under serious competition from other projects, but it is still dominant in market capitalization. Let's plot the market capitalization for the top 10 coins as a barplot to better visualize this.

TOP_CAP_TITLE = 'Top 10 market capitalization'
TOP_CAP_YLABEL = '% of total cap'

# Selecting the first 10 rows and setting the index
cap10 = cap.iloc[:10, :]
cap10 = cap10.set_index(['id'], drop=True)

# Calculating market_cap_perc
cap10 = cap10.assign(market_cap_perc=lambda x: 100 * x['market_cap_usd'] / cap['market_cap_usd'].sum())

# Plotting the barplot with the title defined above 
ax = cap10.plot.bar(title=TOP_CAP_TITLE)

# Annotating the y axis with the label defined above
# ... YOUR CODE FOR TASK 4 ...
ax.set_ylabel(TOP_CAP_YLABEL)
Text(0,0.5,'% of total cap')
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

5. Making the plot easier to read and more informative

While the plot above is informative enough, it can be improved. Bitcoin is too big, and the other coins are hard to distinguish because of this. Instead of the percentage, let's use a log10 scale of the "raw" capitalization. Plus, let's use color to group similar coins and make the plot more informative1.

For the colors rationale: bitcoin-cash and bitcoin-gold are forks of the bitcoin blockchain2. Ethereum and Cardano both offer Turing Complete smart contracts. Iota and Ripple are not minable. Dash, Litecoin, and Monero get their own color.

1 This coloring is a simplification. There are more differences and similarities that are not being represented here.

2 The bitcoin forks are actually very different, but it is out of scope to talk about them here. Please see the warning above and do your own research.

COLORS = ['orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'silver', 'orange', 'red', 'green']

# Plotting market_cap_usd as before but adding the colors and scaling the y-axis  
ax = cap.plot(kind='bar', title='Top 10 market capitalization', logy=True)

# Annotating the y axis with 'USD'
# ... YOUR CODE FOR TASK 5 ...
ax.set_ylabel('USD')

# Final touch! Removing the xlabel as it is not very informative
# ... YOUR CODE FOR TASK 5 ...
ax.get_xaxis().set_visible(False)
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

6. What is going on?! Volatility in cryptocurrencies

The cryptocurrencies market has been spectacularly volatile since the first exchange opened. This notebook didn't start with a big, bold warning for nothing. Let's explore this volatility a bit more! We will begin by selecting and plotting the 24 hours and 7 days percentage change, which we already have available.

volatility = dec6[['id', 'percent_change_24h', 'percent_change_7d']]

# Setting the index to 'id' and dropping all NaN rows
volatility = volatility.set_index('id').dropna()

# Sorting the DataFrame by percent_change_24h in ascending order
volatility = volatility.sort_values('percent_change_24h')

# Checking the first few rows
# ... YOUR CODE FOR TASK 6 ...
print(volatility.head())
               percent_change_24h  percent_change_7d
id                                                  
flappycoin                 -95.85             -96.61
credence-coin              -94.22             -95.31
coupecoin                  -93.93             -61.24
tyrocoin                   -79.02             -87.43
petrodollar                -76.55             542.96

7. Well, we can already see that things are a bit crazy

It seems you can lose a lot of money quickly on cryptocurrencies. Let's plot the top 10 biggest gainers and top 10 losers in market capitalization.

def top10_subplot(volatility_series, title):
    # Making the subplot and the figure for two side by side plots
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 6))
    
    # Plotting with pandas the barchart for the top 10 losers
    volatility_series.head(10).plot(kind='bar', ax=axes[0])
    
    # Setting the figure's main title to the text passed as parameter
    # ... YOUR CODE FOR TASK 7 ...
    fig.suptitle(title)
    
    # Setting the ylabel to '% change'
    # ... YOUR CODE FOR TASK 7 ...
    axes[0].set_ylabel('% change')
    axes[1].set_ylabel('% change')
    
    # Same as above, but for the top 10 winners
    volatility_series[-10:].plot(kind='bar', ax=axes[1])
    
    # Returning this for good practice, might use later
    return fig, ax

DTITLE = "24 hours top losers and winners"

# Calling the function above with the 24 hours period series and title DTITLE  
fig, ax = top10_subplot(volatility, DTITLE)
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

8. Ok, those are... interesting. Let's check the weekly Series too.

800% daily increase?! Why are we doing this tutorial and not buying random coins?1

After calming down, let's reuse the function defined above to see what is going weekly instead of daily.

1 Please take a moment to understand the implications of the red plots on how much value some cryptocurrencies lose in such short periods of time

volatility7d = volatility.sort_values('percent_change_7d')

WTITLE = "Weekly top losers and winners"

# Calling the top10_subplot function
fig, ax = top10_subplot(volatility7d['percent_change_7d'], WTITLE)
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

9. How small is small?

The names of the cryptocurrencies above are quite unknown, and there is a considerable fluctuation between the 1 and 7 days percentage changes. As with stocks, and many other financial products, the smaller the capitalization, the bigger the risk and reward. Smaller cryptocurrencies are less stable projects in general, and therefore even riskier investments than the bigger ones1. Let's classify our dataset based on Investopedia's capitalization definitions for company stocks.

1 Cryptocurrencies are a new asset class, so they are not directly comparable to stocks. Furthermore, there are no limits set in stone for what a "small" or "large" stock is. Finally, some investors argue that bitcoin is similar to gold, this would make them more comparable to a commodity instead.

largecaps = cap.query('market_cap_usd > 10**10')

# Printing out largecaps
# ... YOUR CODE FOR TASK 9 ...
print(largecaps)
             id  market_cap_usd
0       bitcoin    2.130493e+11
1      ethereum    4.352945e+10
2  bitcoin-cash    2.529585e+10
3          iota    1.475225e+10

10. Most coins are tiny

Note that many coins are not comparable to large companies in market cap, so let's divert from the original Investopedia definition by merging categories.

This is all for now. Thanks for completing this project!

# "cap" DataFrame. Returns an int.
# INSTRUCTORS NOTE: Since you made it to the end, consider it a gift :D
def capcount(query_string):
    return cap.query(query_string).count().id

# Labels for the plot
LABELS = ["biggish", "micro", "nano"]

# Using capcount count the biggish cryptos
biggish = capcount('market_cap_usd > 3*10**8')

# Same as above for micro ...
micro = capcount('market_cap_usd < 3*10**8 and market_cap_usd > 5*10**7')

# ... and for nano
nano =  capcount('market_cap_usd < 5*10**7')

# Making a list with the 3 counts
values = [biggish, micro, nano]

# Plotting them with matplotlib 
# ... YOUR CODE FOR TASK 10 ...
plt.bar(values)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-83-c482fdf68251> in <module>()
     22 # Plotting them with matplotlib 
     23 # ... YOUR CODE FOR TASK 10 ...
---> 24 plt.bar(values)

/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py in bar(*args, **kwargs)
   2646                       mplDeprecation)
   2647     try:
-> 2648         ret = ax.bar(*args, **kwargs)
   2649     finally:
   2650         ax._hold = washold

/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1715                     warnings.warn(msg % (label_namer, func.__name__),
   1716                                   RuntimeWarning, stacklevel=2)
-> 1717             return func(ax, *args, **kwargs)
   1718         pre_doc = inner.__doc__
   1719         if pre_doc is None:

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py in bar(self, *args, **kwargs)
   1963                 break
   1964         else:
-> 1965             raise exps[0]
   1966         # if we matched the second-case, then the user passed in
   1967         # left=val as a kwarg which we want to deprecate

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py in bar(self, *args, **kwargs)
   1955         for matcher in matchers:
   1956             try:
-> 1957                 dp, x, height, width, y, kwargs = matcher(*args, **kwargs)
   1958             except TypeError as e:
   1959                 # This can only come from a no-match as there is

TypeError: <lambda>() missing 1 required positional argument: 'height'
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">