DEV Community

Cover image for Python: Bitcoin price trend with Matplotlib

Posted on

Python: Bitcoin price trend with Matplotlib

If you are a long term trading, you are not interested in the day-to-day rates. You can get the historic price of bitcoin by year.

I pick Python because that's my go to language for quick scripts.

Collect data

You can get the JSON formatted data and parse it into a Python list. In the code below we use the requests module to do that.

We are only interested in the same day in each year, everything else is noise.I picked the day September 10. The data itself starts from 2014, you can't go further back than that, because they don't have that data.

import json
import requests
from bs4 import BeautifulSoup
import csv
import sys
from time import sleep
from time import gmtime, strftime
import matplotlib.pyplot as plt
import seaborn as sns

enddate = strftime("%Y%m%d", gmtime()) 
r  = requests.get("{0}".format(enddate))
data = r.text

soup = BeautifulSoup(data, "html.parser")
table = soup.find('table', attrs={ "class" : "table"})

prices = []

for row in table.find_all('tr'):
    addPrice = False
    tag = row.findAll('td')
    for val in tag:
        value = val.text

        if "Sep 10" in value:
            addPrice = True

    if addPrice == True:
        prices.append( tag[3].text )

# flip list, months are in reverse order
prices = prices[::-1]

We flip the pricing data, because the months start returning in reverse order.

Sep 10, 2019
Sep 10, 2018
Sep 10, 2017
Sep 10, 2016
Sep 10, 2015
Sep 10, 2014

Create plot

Ok so now that you have the pricing data you can create the plot.

x = list(range(0, len(prices)))

plt.title('Bitcoin price from 2014')
plt.ylabel('Price in USD')
plt.xlabel('Years from 2014'), prices)

That gives us:

Alt Text

So is it a good investment? That's for you to decide, this is not financial advice.

Related links:

Top comments (0)