-->

Wednesday 18 April 2018

Simple & compact Python Bitcoin ticker

Hi all,

Today, just fun.

I wrote a simple Bitcoin ticker. The concept is simple :

  • using Python
  • calling public rest service for Bitcoin rates
  • using matplotlib
  • updating in real time, 1 second interval just for fun

    Using Python

    It’s not breaking news, Python has a great success in data manipulation, exploration, visualization and science. Next time, I’ll show you some nice map rendering with Jupyter Notebooks, which I recommend for any data science project.

    Here are the imports I used for this demonstration :

    Public Rest services for Bitcoin rates

    You can easily find rest services providing data about Bitcoin. I chose to use this rest call : https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR&e=Coinbase&extraParams=your_app_name

    Pretty simple, this service returns some compact json data. In this use case, I will parse the json object and retrieve the USD rate only.

    {"USD":8089.97,"EUR":6556.01}

    Of course it is recommended to use data from different services, coming from different providers in order to have multiple Bitcoin rates and build something like an average.

    The output

    The output, with matplotlib, is a simple window displaying the graph and updating in real time. For this example, I chose a 1 second refresh rate (pretty useless but this was fun to see the high Bitcoin volatility).

    Look at this accelerated gif, created from a record on April 18 2108, displaying the rates for approx 20 minutes. Sorry for the bad recording quality, I’ll do better soon.

    8pris-bjbkl

    The script

    You can simply copy and paste this script, it will simply work. Just be sure to install the required packages. Just for information, I’m using Visual Studio Code for this use case.

    import numpy as np  
    import requests  
    import datetime  
    import time  
    import calendar  
    import matplotlib.pyplot as plt  
    from matplotlib import animation  
       
    x = np.arange(100000) # 100000 polling points  
    usd = []  
      
    fig, ax = plt.subplots()  
    line, = ax.plot([], [], 'k-')  
    ax.margins(0.05)  
       
    def init():  
      line.set_data(x[:2],usd[:2])  
      return line,  
       
    def animation(i):  
      time.sleep(1)  
      url = 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR&e=Coinbase&extraParams=your_app_name'    
      r = requests.get(url)  
      r.json()  
      data = r.json()  
      usd.append(float(data['USD']))  
         
      win = 86400  
      imin = min(max(0, i - win), x.size - win)  
      xdata = x[imin:i]  
      ydata = usd[imin:i]  
      
      line.set_data(xdata, ydata)  
      ax.relim()  
      ax.autoscale()  
      return line,  
       
    anim = animation.FuncAnimation(fig, animation, init_func=init, interval=25)  
    plt.show()  
              

    No comments: