Stock Tracker

Stock Tracker

The New York Stock Exchange sells stocks 5 days a week. During this time the price of a stock can move based on how many people are buying or selling a stock at any given time. Let’s turn the BrainPad into a stock tracker that tracks specific stocks and alerts us when they’re over a certain price.

Prerequisite

You must have a basic understanding of coding and have completed the Drawing lesson.

The API

Our demo program uses FREE stock quotes from finnhub.io. The free service allows up to 50 quotes per minute that are called using a URL with an API Key they provide when you sign up. The data returned is in JSON format. In our example, we will pause our program for 1200 milliseconds before requesting another quote. You’ll need to create an account to get the FREE API Key. Once you have the Key, change the URL below to include a STOCK SYMBOL and YOUR API KEY. You can paste the URL into a web browser to see the result. Once we know the API is working we can build the complete program.

https://finnhub.io/api/v1/quote?symbol=STOCK SYMBOL &token=YOUR API KEY 

As an example we asked for a quote on IBM stock, this is the JSON data received:

We can use 2 parallel arrays/lists to store the stocks and target price we want to track.

Python

# List in Python
stock = ["AAPL", "GOOGL", "EXTR","MSFT", "TSLA", "RCL"]
target = [190, 120, 25, 340, 270, 100]

C#

//Array in C#
string[] stock = { "AAPL", "GOOGL", "EXTR", "MSFT", "TSLA",  "RCL" };
double[] target = { 190, 124, 25, 335, 270,  100};

The first array/list will hold the symbols of the stocks we want to look up. Any stock symbols can be added to the stock array/list. Keep in mind that only 50 quotes per minute are allowed with the FREE service. The second array/list, target, will hold the corresponding target price of the stocks. When the quote we receive is higher than our target price the buzzer will sound, and display the ‘^‘ character in front of the price.

Connecting to the Internet

The program connects to the Internet from within the code. This is done by creating an HttpClient() in C# and importing urllib3 in Python. The JSON library also needs to be added in both languages. The program will read the JSON data sent back to and select the “c” property, which is the stock’s current price.

Python

import urllib3
import json

C#

using System.Text.Json;

Python

http = urllib3.PoolManager()

while True:
    for i in range (len(stock)):
        BrainPad.Display.Clear(0)
        url = "https://finnhub.io/api/v1/quote?symbol={}&token=YOUR API KEY".format(stock[i])
        response = http.request('GET',url)
        data=json.loads(response.data)
        stockQuote = (data['c'])

C#

var httpClient = new HttpClient();

while (true) {
    for (int i = 0; i < stock.Length; i++){
        BrainPad.Display.Clear(0);
        var url = string.Format("https://finnhub.io/api/v1/quote?symbol={0}&token=YOUR API KEY",stock[i]);
        var response = await httpClient.GetStringAsync(url);
        var data = JsonDocument.Parse(response);
        var stockQuote = data.RootElement.GetProperty("c");

The stockQuote variable is currently a JSON object in C# so it will need to be converted to a double so the current price can be compared to the numbers inside the target[] array, Call this variable price. Python already stores the value as a number so we can continue to use stockQuote. Inside the while loop, the code checks each time to see if the target price is greater than what was retrieved from the Internet. If it does the BrainPad will beep twice and blink the onboard LED it will also add the ^ character in front of the price on the display. Otherwise, it will just display the stock and price with a very short beep.

Python

if stockQuote > target[i]:
            BrainPad.System.Beep('p', 500, 500)
            BrainPad.System.Beep('p', 200, 500)
            BrainPad.Led.Set(100, 100, 4)
            BrainPad.Display.DrawTextScale("^{}".format(stockQuote), 1, 0, 30, 3, 3)
        else:
            BrainPad.Display.DrawTextScale("{}".format(stockQuote), 1, 0, 30, 3, 3) 
            BrainPad.System.Beep('p', 200, 10)

C#

 var price = stockQuote.GetDouble();
        if ( price > target[i]){
            BrainPad.System.Beep('p', 500, 500);
            BrainPad.System.Beep('p', 200, 500);
            BrainPad.Led.Set(100, 100, 4);
            BrainPad.Display.DrawTextScale(string.Format("^{0}",price), 1, 0, 30, 3, 3);
        }
        else{
            BrainPad.Display.DrawTextScale(string.Format("{0}",price), 1, 0, 30, 3, 3);
            BrainPad.System.Beep('p', 200, 10);
        }       

Finally, add the stock symbol and position it above the price on the display. Add a pause at the very end to give the user time to see the display, and to keep the JSON calls under 50 per minute.

Python

BrainPad.Display.DrawTextScale(stock[i],1,0,0,3,3)
BrainPad.Display.Show()
BrainPad.System.Wait(1200)

C#

BrainPad.Display.DrawTextScale(stock[i], 1, 0, 0, 3, 3);
BrainPad.Display.Show();  
BrainPad.System.Wait(1200);

Complete Code

Python

import urllib3
import json

from DUELink.DUELinkController import DUELinkController

availablePort = DUELinkController.GetConnectionPort()
http = urllib3.PoolManager()
BrainPad = DUELinkController(availablePort)

#List of stocks to track and target price
stock = ["AAPL", "GOOGL", "EXTR","MSFT", "TSLA", "RCL"]
target = [190, 126, 25, 340, 270, 100]

while True:
    for i in range (len(stock)):
        BrainPad.Display.Clear(0)
        url = "https://finnhub.io/api/v1/quote?symbol={}&token=YOUR API KEY".format(stock[i])
        response = http.request('GET',url)
        data=json.loads(response.data)
        stockQuote = (data['c'])

        if stockQuote > target[i]:
            BrainPad.System.Beep('p', 500, 500)
            BrainPad.System.Beep('p', 200, 500)
            BrainPad.Led.Set(100, 100, 4)
            BrainPad.Display.DrawTextScale("^{}".format(stockQuote), 1, 0, 30, 3, 3)
        else:
            BrainPad.Display.DrawTextScale("{}".format(stockQuote), 1, 0, 30, 3, 3) 
            BrainPad.System.Beep('p', 200, 10)
        
        BrainPad.Display.DrawTextScale(stock[i],1,0,0,3,3)
        BrainPad.Display.Show()
        BrainPad.System.Wait(1200) 

C#

using GHIElectronics.DUELink;
using System.Text.Json;

var availablePort = DUELinkController.GetConnectionPort();
var httpClient = new HttpClient();
var BrainPad = new DUELinkController(availablePort);

//Array of stocks to track and target price
string[] stock = { "AAPL", "GOOGL", "EXTR", "MSFT", "TSLA",  "RCL" };
double[] target = { 188, 124, 25, 340, 266, 82};
    
while (true) {
    for (int i = 0; i < stock.Length; i++){
        BrainPad.Display.Clear(0);
        var url = string.Format("https://finnhub.io/api/v1/quote?symbol={0}&token=YOUR API KEY",stock[i]);
        var response = await httpClient.GetStringAsync(url);
        var data = JsonDocument.Parse(response);
        var stockQuote = data.RootElement.GetProperty("c");

        var price = stockQuote.GetDouble();
        if ( price > target[i]){
            BrainPad.System.Beep('p', 500, 500);
            BrainPad.System.Beep('p', 200, 500);
            BrainPad.Led.Set(100, 100, 4);
            BrainPad.Display.DrawTextScale(string.Format("^{0}",price), 1, 0, 30, 3, 3);
        }
        else{
            BrainPad.Display.DrawTextScale(string.Format("{0}",price), 1, 0, 30, 3, 3);
            BrainPad.System.Beep('p', 200, 10);
        }           
        BrainPad.Display.DrawTextScale(stock[i], 1, 0, 0, 3, 3);
        BrainPad.Display.Show();  
        BrainPad.System.Wait(1200);
    }
}

What’s Next?

Now that we can grab the data online from the stock website, show it on display, and alert us when it hits a certain price, can you think of a way to use a NeoPixel Matrix to make a bigger display, maybe make it scroll like a real stock ticker?


Content Licensing
Newsletter

Twitter Feed
Hot off the press!