Calculate Average Fee per Bitcoin Transaction with Python

PlutoHash
3 min readMar 26, 2021

In this post we’ll see how it’s possible, with just a few lines in Python, to analyze how the average daily cost of fees changes over time, from one year to the next but also from one month to the next. As a reminder, we are analyzing the bitcoin blockchain.

This article was originally taken from the PlutoHash blog. You can register on our website to get access to real blockchain data and perform analysis with Python. No configuration required, just sign up for our Beta Testers program.

If you are interested this is the link: Beta Testers Program.

Let’s start by importing the libraries.

import blocksci 
import pandas as pd
import seaborn
import matplotlib.pyplot as plt
import matplotlib.ticker
import collections import numpy as np

Instantiate the chain object. This will allow us to have access to all transactions on the bitcoin blockchain.

chain = blocksci.Blockchain("/BlockSci/config_file")

We also use converter to express the value of fees in USD. Exchange rates are provided by CoinDesk.

converter = blocksci.CurrencyConverter()

We use the fees_by_year() function to define the year of interest and then be able to apply it to different years. This is the code:

def fees_by_year(year):      blocks = chain.range(year) 
fees = blocks.fee / blocks.tx_count
times = blocks.time
df = pd.DataFrame({“Fee”:fees}, index = times)
df = converter.satoshi_to_currency_df(df, chain)
ax = df.resample(“d”).mean().plot(legend=False) return df, ax

The range() method extracts all blocks in the range specified by the blockchain (in this case we will use years to define the time horizon). Fees per block are calculated by dividing the total fees for each block by the total number of transactions validated in that specific block.

Now, we can apply the function by defining the year of our interest. Let’s try the years 2017, 2019, and 2020.

df_2017,ax_2017 = fees_by_year("2017")
average daily fees 2017
df_2019,ax_2019 = fees_by_year("2019")
average daily fees 2019
df_2020,ax_2020 = fees_by_year("2020")
average daily fees 2020

From the chart we can see that the average fee per transaction in 2019 has remained essentially stable. On the other hand, if we look at 2017, there has been a noticeable increase in the last few months. The reason for this is easy to guess, because as we know there was a significant growth in the popularity of bitcoin in 2017, this meant more purchases and an increase in competition for transaction validation. As we can see something similar happened in the last months of 2020.

Would you like to analyze the bitcoin blockchain using Python?

Apply to our Beta Tester Program!

--

--