Raspberry Pi Stock Ticker

I love tinkering with displays, as you can see with my post about the DLR2416, so I purchased Adafruit’s  2.2″ PiTFT plug-in display from www.pimoroni.com to try out.

This display works great with my Raspberry Pi B+ or A+. To get things started I followed the tutorial/guide on Adafruit’s website here. I’ll not go into detail regarding getting the PiTFT working with your Pi as Adafruit covers it very well.

For network/internet connection I used a Pi-compatable USB wifi dongle, again I’ll not go into detail with installing that, as it differs a great deal depending on what make/model dongle you get your hands on. There’s tons of stuff on the internet discussing wifi dongles with the Raspberry Pi. Also you could always just use an ethernet cable.

Once you get your PiTFT display working with the example code from Adafruit, there’s only a few steps to take to turn your new display into a stock ticker.

Install pygame. It’s usually installed as standard with Raspbian. You can check by running Python at the command line, then the following at the interactive shell:
>>> import pygame
If nothing happens then you already have pygame installed, else you’ll get an error like:
ImportError: No module named pygame
If it isn’t installed, then quit Python and do a:
$ sudo apt-get install python-pygame

Next we need to install Yahoo’s API “ystockquote”, at the console:
$ pip install ystockquote

There is plenty of example code here on Python’s website if you want to have a mess about, or see how it can be used.

I used a font from www.dafont.com called “CodeNewRoman b”, you can download that here. Copy the font file into the same place as the Python script.

Now it’s just a case of saving and running the Python script below:
$ python PiStockTFT.py

#!/usr/bin/env python

import os
import time
import socket
import pygame
import ystockquote

def main():
    WHITE = (255,255,255)
    GREY = (240,240,240)
    BLACK = (0,0,0)
    BLUE = (0,145,255)
    RED = (255,0,0)
    GREEN = (0,255,0)
    YELLOW = (255,255,0)
    tickersymbols = ['LWRF.L','BTG.L','AAPL','AUE.L']
    print("= StockPi stock ticker from www.warmcat.uk =")
    print("Initialising TFT...")
    os.putenv('SDL_FBDEV', '/dev/fb1')
    lcd = pygame.display.set_mode((320,240))
    myfont = pygame.font.Font("CodeNewRoman_b.otf", 32)
    myfont2 = pygame.font.Font("CodeNewRoman_b.otf", 24)
    keep_running = True
        textToPrint = myfont.render("Fetching data...", 0, WHITE)
        lcd.blit(textToPrint, (10,210))
        while keep_running:
            x = 0
            pygame.draw.circle(lcd, YELLOW, (307,12), 6, 0)
            print("Fetching data...")
            for tickerSymbol in tickersymbols:
                    allInfo = ystockquote.get_all(tickerSymbol)
                    textToPrint = myfont.render("Error...", 0, WHITE)
                    lcd.blit(textToPrint, (10,210))
                    print("Connection Error, waiting 20 seconds.")
                price = float(allInfo["price"])
                change = float(allInfo["change"])
                percent = change/(change + price)*100
                peratio = allInfo["price_earnings_ratio"]
                if change == 0:
                    ourColour = GREY
                elif change > 0:
                    ourColour = GREEN
                    ourColour = RED
                print tickerSymbol + "\t= %3.2f (%+0.2f, %+0.2f%%) P/E %s" % (price, change, percent, peratio)
                stockPrice = ("{:>6.2f}".format(price))
                stockChanges = ("({:>+5.2f}, {:>+5.2f}%)".format(change, percent))
                if x == 0:
                textToPrint = myfont.render(tickerSymbol, 0, WHITE)
                lcd.blit(textToPrint, (30,7+x))
                textToPrint = myfont.render(stockPrice, 0, ourColour)
                lcd.blit(textToPrint, (160,5+x))
                textToPrint = myfont2.render(stockChanges, 0, ourColour)
                lcd.blit(textToPrint, (62,32+x))
            time.sleep(60) #seconds (so every 1 min)
    except KeyboardInterrupt:
        keep_running = False
        print("Oh my god, it's all gone to shit!")
        textToPrint = myfont.render("ERROR...", 0, WHITE)
        lcd.blit(textToPrint, (10,210))

if __name__ == '__main__': main()

Here’s how it looks:

I also used the same type of display for a train map project utilising the National Rail API, but alas did not document it:

Leave a Reply

Your email address will not be published. Required fields are marked *