A currency exchange rate tracker using a Raspberry Pi

September 11, 2020

tutorial tech

In this step-by-step guide, we will be setting up a Raspberry Pi to track a currency exchange rate and then using Grafana to display the data in a graph.

This article will cover:

  1. Installing InfluxDB on the Pi
  2. Writing a simple python script to fetch the exchange rate data from an API and write it to a database
  3. Installing Grafana on the Pi
  4. Setting up Grafana to read the data and display it in a graph
  5. Getting the script to run at regular intervals, automatically

While this tutorial is specific to the task at hand, it's faily simple to extrapolate the tools we'll use to get your Raspberry Pi doing lots of other cool data tracking.

I'll assume you already have a Raspberry Pi set up and ready to go.

Let's get started!


Up-to-date

Before starting any new project on the Pi, it's always best to make sure everything is up-to-date.

Run the following commands

sudo apt update
sudo apt upgrade

Installing InfluxDB

This is what we will use to store the exchange rate data that we collect over time.

InfluxDB is an open source time series database. This makes it an ideal choice for tracking something which is going to vary over time (like a currency), because each data point contains an automatic timestamp.

What's more, Grafana works nicely with it, which makes everything that bit simpler.

First, let's grab the InfluxDB repository key and add it to the Pi.

wget -qO- https://repos.influxdata.com/influxdb.key | sudo apt-key add -

Next, we'll add the repository to our sources list.

echo "deb https://repos.influxdata.com/debian buster stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

Because we've just updated our sources list, we need to run another update.

sudo apt update

Now let's actually install InfluxDB

sudo apt install influxdb

and get it starting when we boot up the Pi.

sudo systemctl unmask influxdb
sudo systemctl enable influxdb

All that remains is for us to actually start the InfluxDB service.

sudo systemctl start influxdb

Now we're ready to set up a database so that we can start writing some data to it. This is actually a lot more straightforward than it sounds.

First, let's launch the InfluxDB command line tool

influx

Now let's create a new database. Because I'm going to be tracking Norwegian kroner, I'll call mine nokvalue, but feel free to call yours anything you'd like.

CREATE DATABASE nokvalue

Now we need to create a user to interact with the database, and a password.

CREATE USER "dom" WITH PASSWORD "thisshouldbemoresecure"

and assign that user dom all the privileges they will need to interact with the nokvalue database

GRANT ALL ON "nokvalue" to "dom"

and quit.

quit

Because we'll be writing a short python script to carry out our data collection, we need to install the necessary library

sudo apt install python3-influxdb

That's it! We're now ready to start writing some code.


Writing some python

You can either write this script directly on the Pi or on your normal machine.

I tend to do the latter and then just copy the .py file over to the Pi using something like filezilla.

In the interests of brevity I will just paste the entire script here but you are free to edit it as you see fit, depending on the currency you will be tracking.

We'll be using the Frankfurter API to get our data, but again, you can use any API you like. I just like Frankfurter because it doesn't require an API key to use.

I've also just hard-coded in the GET request as I won't need to be changing the parameters. This is generally bad practice as you should really use variables for the parameters, but it gets the job done for now.

import requests
from influxdb import InfluxDBClient


def get_nok_value():
    response = requests.get('https://api.frankfurter.app/latest?amount=1&from=GBP&to=NOK')
    if response.status_code == 200:
        response = response.json()
        nok = response["rates"]
        nok = nok["NOK"]
        nok_data = [
                {
                    "measurement": "nok_value",
                    "fields": {
                            "value": float(nok)
                    }
                }
        ]
        client = InfluxDBClient('localhost', 8086, 'dom', 'thisshouldbemoresecure', 'nokvalue')
        client.write_points(nok_data)
    elif response.status_code != 404:
        print("Error making API call")

get_nok_value()

The GET request is fetching the amount of Norwegian Kroner equivalent to 1 GBP. It is the latest value, which gets updated once a day.

Don't forget to change the details of this line:

client = InfluxDBClient('localhost', 8086, 'dom', 'thisshouldbemoresecure', 'nokvalue')

to match the details you entered earlier when setting up the database. Replace 'dom', 'thisshouldbemoresecure', 'nokvalue' with your own USERNAME, PASSWORD, DATABASE NAME respectively.

Save the file in (or copy it over to) the home directory ~/ of your pi. I've called mine nok_value.py

Now it's time to run it and start seeing some data!

python3 ~/nok_value.py

Installing Grafana

Hopefully our python script made the API call and received the latest value for whichever currency you picked. It then wrote this value to our new database.

But the whole idea is that we want to see how the currency fluctuates over time, so to do this we want to plot the data points on a graph which we can glance at.

This is where Grafana comes in.

Let's get Grafana set up on our Pi.

Download the Grafana package file

wget https://dl.grafana.com/oss/release/grafana_6.6.1_armhf.deb

and install it.

sudo dpkg -i grafana_6.6.1_armhf.deb

Similarly to how we set up InfluxDB, we want Grafana to start when we boot up the Pi. Enter these two commands:

sudo systemctl enable grafana-server
sudo systemctl start grafana-server

Now while the Raspberry Pi is very useful, we don't really want to be logging in and viewing our data directly on it each time we want to look at our graph.

The point of this setup is that we can leave the Pi quietly collecting data for days and weeks at a time, and view the graph at our convenience from a phone or laptop.

To achieve this, we need to set up a couple of things to allow access.

First, we need to find out what the IP address is of our Pi within our private network. On your Pi, run

hostname -I

and note down the IP address.

Now on another computer, try to visit this address in a browser by typing in

http://<YOUR-PI-IP-ADDRESS>:3000

This should take you to a login page for Grafana. The default login credentials are

username: admin

password: admin

After logging in, Grafana will ask you to change your password. Do this, hit save, and then you're in!


Visualizing our data with Grafana

In order to see our data on a graph, we need to tell Grafana where to look, and exactly what to look for.

In our case there isn't a lot of data at all which will make these next few steps a lot more straightforward.

You can follow the onboarding process which Grafana suggests to you, or use the sidebar to complete the following steps.

Create a data source

  1. Click 'Add data source' and select 'InfluxDB'
  2. Under the 'HTTP' section, into the 'URL' field enter http://localhost:8086
  3. Under the 'InfluxDB Details' section, enter the details of the database which you created earlier on when installing InfluxDB to the Pi.

The setup should look something like this:

Grafana Database Setup

  1. Click 'Save & Test', and you should be greeted with some nice green notifications letting you know that Grafana was able to successfully connect to database.

Create a dashboard

  1. Select 'Add Query'
  2. In the 'FROM' row, click 'select measurement', and there should only be one option available. In my case, it's 'nok_value'.
  3. In the 'SELECT' row, click the + button, hover over 'Aggregrations', and select 'Distinct'
  4. In the 'ALIAS BY' row, enter a name for this new query, e.g. NOK Value.

Grafana Dashboard Setup

  1. All that remains is to give our dashboard tile a title. Click the cog icon on the sidebar, and enter a title of your choosing.
  2. Now at the top of your screen, hit the save icon.

A new graph should now show up in your dashboard. There should only be one data point (as we've only run our python script once), but that's enough to show that everything is working as expected.

Now it's time to get our python script running automatically at set intervals, so we can sit back and watch the data roll in.


Getting the script to run automatically

Once again, this might seem a lot more daunting than it actually is. Setting up a task to run automatically is actually pretty easy, especially if it's only once a day, like ours will be.

Back in the terminal of your Pi, enter:

sudo crontab -e

You should be given a choice of which editor you want to use to edit this file, and unless you have another preference, just select the default nano.

As I mentioned, we'll be setting ours up to run once a day. Depending on the metric you're tracking you may want to change this to something a lot more frequent, but it's fine for this use case.

We'll set ours up to run at 15:00 every day.

Go to the bottom of the file, and write the following (changing the file name to whatever you called your python script).

0 15 * * * python3 /home/pi/nok_value.py

Then press CTRL + X, then Y, then Enter. This will save your changes, and your script will run either at 15:00 today, or the next day if it is currently after 15:00 today.

That's it! Your data will be automatically written to the database once a day, and whenever you want to see it presented in your graph, just head to

http://<YOUR-PI-IP-ADDRESS>:3000

login, and there it will be.


There is obviously an awful lot more you could be using these tools for, but I hope this has been a straightforward but useful introduction.

Sign up for Spark

Spark is one idea, once a week, emailed to you.