Raspberry Pi Stock Ticker

UPDATE: Yahoo’s ystockquote is no longer available. However one person emailed me advising that it’s still possible to obtain Yahoo’s stock by parsing data with the python package “BeautifulSoup”.

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():
    #Colours
    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("\n============================================")
    print("= StockPi stock ticker from www.warmcat.uk =")
    print("============================================\n")
    print("Initialising TFT...")
    os.putenv('SDL_FBDEV', '/dev/fb1')
    pygame.init()
    pygame.mouse.set_visible(False)
    lcd = pygame.display.set_mode((320,240))
    lcd.fill(BLACK)
    pygame.display.update()
    myfont = pygame.font.Font("CodeNewRoman_b.otf", 32)
    myfont2 = pygame.font.Font("CodeNewRoman_b.otf", 24)
    keep_running = True
    try:
        textToPrint = myfont.render("Fetching data...", 0, WHITE)
        lcd.blit(textToPrint, (10,210))
        pygame.display.update()
        while keep_running:
            x = 0
            pygame.draw.circle(lcd, YELLOW, (307,12), 6, 0)
            pygame.display.update()
            print("Fetching data...")
            for tickerSymbol in tickersymbols:
                try:
                    allInfo = ystockquote.get_all(tickerSymbol)
                except:
                    textToPrint = myfont.render("Error...", 0, WHITE)
                    lcd.blit(textToPrint, (10,210))
                    pygame.display.update()
                    print("Connection Error, waiting 20 seconds.")
                    time.sleep(20)
                    pass
                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
                else:
                    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:
                    lcd.fill(BLACK)
                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))
                x=x+58;
            pygame.display.update()
            print("Done.")
            time.sleep(60) #seconds (so every 1 min)
    except KeyboardInterrupt:
        print("\nQuitting...")
        keep_running = False
    else:
        print("Oh my god, it's all gone to shit!")
        lcd.fill(BLACK)
        textToPrint = myfont.render("ERROR...", 0, WHITE)
        lcd.blit(textToPrint, (10,210))
        pygame.display.update()
        raise
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:

6 thoughts on “Raspberry Pi Stock Ticker

  1. I can’t for the life of me get this to work. This is the error I’m getting. I’ve run it with and without sudo before it and nothing is working. I have the Yahoo stock installed too. Please help.

    Initialising TFT…
    Fetching data…
    Connection Error, waiting 20 seconds.
    Traceback (most recent call last):
    File “PiStockTFT.py”, line 87, in
    if __name__ == ‘__main__’: main()
    File “PiStockTFT.py”, line 51, in main
    price = float(allInfo[“price”])
    UnboundLocalError: local variable ‘allInfo’ referenced before assignment

          1. You just need to change the URL in lines 22, 38, and 53. Also change the stock name in lines 81, 88, 95. Email me if you need more help.

        1. Thanks for this, Daniel. Any tips on how to get it work with Bitcoin? I noticed the ‘BTC-USD’ page on Yahoo Finance doesn’t work.. maybe pulling from the CoinMarketCap API?

Leave a Reply

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