Roman Orac’s article “Cryptocurrency Analysis with Python — Buy and Hold,” featured in Towards Data Science, provides a detailed analysis of cryptocurrency investments using Python. Orac focuses on assessing the profitability of cryptocurrencies like Bitcoin, Ethereum, and Litecoin over a specific period. He employs Python for data retrieval, manipulation, and visualization, highlighting techniques such as extracting closing prices and analyzing returns using the buy-and-hold strategy. The article serves as both an informative guide on cryptocurrency analysis and a practical demonstration of Python’s application in financial data analysis.
For more details, you can read the full article on Towards Data Science or read the full article below.
Requirements
For other requirements, see my previous blog post in this series.
Getting the data
To get the latest data, go to the previous blog post, where I described how to download it using Cryptocompare API. You can also use the data I work within this example.
First, let’s download hourly data for BTC, ETH, and LTC from Coinbase exchange. This time we work with an hourly time interval as it has higher granularity. Cryptocompare API limits response to 2000 samples, which is 2.7 months of data for each coin.import pandas as pddefget_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date):
return ‘%s_%s_%s_%s_%s.csv’ % (from_symbol, to_symbol, exchange, datetime_interval, download_date)defread_dataset(filename):
print(‘Reading data from %s’ % filename)
df = pd.read_csv(filename)
df.datetime = pd.to_datetime(df.datetime) # change to datetime
df = df.set_index(‘datetime’)
df = df.sort_index() # sort by datetime
print(df.shape)
return df
Load the data
df_btc = read_dataset(get_filename(‘BTC’, ‘USD’, ‘Coinbase’, ‘hour’, ‘2017-12-24’))
df_eth = read_dataset(get_filename(‘ETH’, ‘USD’, ‘Coinbase’, ‘hour’, ‘2017-12-24’))
df_ltc = read_dataset(get_filename(‘LTC’, ‘USD’, ‘Coinbase’, ‘hour’, ‘2017-12-24’))df_btc.head()
Extract closing prices
We are going to analyze closing prices, which are prices at which the hourly period closed. We merge BTC, ETH and LTC closing prices to a Dataframe to make analysis easier.df = pd.DataFrame({‘BTC’: df_btc.close,
‘ETH’: df_eth.close,
‘LTC’: df_ltc.close})df.head()
Analysis
Basic statistics
In 2.7 months, all three cryptocurrencies fluctuated a lot as you can observe in the table below.
For each coin, we count the number of events and calculate mean, standard deviation, minimum, quartiles, and maximum closing price.
Observations
- The difference between the highest and the lowest BTC price was more than $15000 in 2.7 months.
- The LTC surged from $48.61 to $378.66 at a certain point, which is an increase of 678.98%.
df.describe()
Let’s dive deeper into LTC
We visualize the data in the table above with a box plot. A box plot shows the quartiles of the dataset with points that are determined to be outliers using a method of the inter-quartile range (IQR). In other words, the IQR is the first quartile (25%) subtracted from the third quartile (75%).
On the box plot below, we see that LTC closing hourly price was most of the time between $50 and $100 in the last 2.7 months. All values over $150 are outliers (using IQR). Note that outliers are specific to this data sample.import seaborn as snsax = sns.boxplot(data=df[‘LTC’], orient=“h”)
Histogram of LTC closing price
Let’s estimate the frequency distribution of LTC closing prices. The histogram shows the number of hours LTC had a certain value.
Observations
- LTC closing price was not over $100 for many hours.
- it has right-skewed distribution because a natural limit prevents outcomes on one side.
- blue dashed line (median) shows that half of the time closing prices were under $63.50.
df[‘LTC’].hist(bins=30, figsize=(15,10)).axvline(df[‘LTC’].median(), color=‘b’, linestyle=‘dashed’, linewidth=2)
Visualize absolute closing prices
The chart below shows the absolute closing prices. It is not of much use as BTC closing prices are much higher than prices of ETH and LTC.df.plot(grid=True, figsize=(15, 10))
Visualize relative changes in closing prices
We are interested in a relative change of the price rather than in absolute price, so we use three different y-axis scales.
We see that closing prices move in tandem. When one coin closing price increases so do the other.import matplotlib.pyplot as plt
import numpy as npfig, ax1 = plt.subplots(figsize=(20, 10))
ax2 = ax1.twinx()
rspine = ax2.spines[‘right’]
rspine.set_position((‘axes’, 1.15))
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
fig.subplots_adjust(right=0.7)df[‘BTC’].plot(ax=ax1, style=‘b-‘)
df[‘ETH’].plot(ax=ax1, style=‘r-‘, secondary_y=True)
df[‘LTC’].plot(ax=ax2, style=‘g-‘)# legend
ax2.legend([ax1.get_lines()[0],
ax1.right_ax.get_lines()[0],
ax2.get_lines()[0]],
[‘BTC’, ‘ETH’, ‘LTC’])
Measure the correlation of closing prices
We calculate the Pearson correlation between the closing prices of BTC, ETH, and LTC. Pearson correlation is a measure of the linear correlation between two variables X and Y. It has a value between +1 and −1, where 1 is the total positive linear correlation, 0 is no linear correlation, and −1 is the total negative linear correlation. The correlation matrix is symmetric so we only show the lower half.
Sifr Data daily updates Pearson correlations for many cryptocurrencies.
Observations
- Closing prices aren’t normalized, see Log Returns, where we normalize closing prices before calculating correlation,
- BTC, ETH and LTC were highly correlated in the past 2 months. This means, when BTC closing price increased, ETH and LTC followed.
- ETH and LTC were even more correlated with 0.9565 Pearson correlation coefficient.
import seaborn as sns
import matplotlib.pyplot as plt# Compute the correlation matrix
corr = df.corr()# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(10, 10))# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, annot=True, fmt = ‘.4f’, mask=mask, center=0, square=True, linewidths=.5)
Buy and hold strategy
Buy and hold is a passive investment strategy in which an investor buys a cryptocurrency and holds it for a long period, regardless of fluctuations in the market.
Let’s analyze returns using the Buy and hold strategy for the past 2.7 months. We calculate the return percentage, where t represents a certain period and price0 is the initial closing price:
df_return = df.apply(lambda x: x / x[0])
df_return.head()
Visualize returns
We show that LTC was the most profitable for the period between October 2, 2017 and December 24, 2017.df_return.plot(grid=True, figsize=(15, 10)).axhline(y = 1, color = “black”, lw = 2)
Conclusion
The cryptocurrencies we analyzed fluctuated a lot but all gained in a given 2.7 months period.