/ CircuitStonks / code.py
code.py
1 # SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import board 7 from digitalio import DigitalInOut 8 from adafruit_esp32spi import adafruit_esp32spi 9 from adafruit_esp32spi import adafruit_esp32spi_wifimanager 10 from adafruit_featherwing import minitft_featherwing 11 import terminalio 12 from adafruit_display_text import label 13 import displayio 14 15 minitft = minitft_featherwing.MiniTFTFeatherWing() 16 17 # Get wifi details and more from a secrets.py file 18 try: 19 from secrets import secrets 20 except ImportError: 21 print("WiFi secrets are kept in secrets.py, please add them there!") 22 raise 23 24 # If you are using a board with pre-defined ESP32 Pins: 25 esp32_cs = DigitalInOut(board.D13) 26 esp32_ready = DigitalInOut(board.D11) 27 esp32_reset = DigitalInOut(board.D12) 28 spi = board.SPI() 29 esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 30 wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets) 31 32 # Symbol "INX" for S&P500, "DJIA" for Dow 33 DATA_SOURCE = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&apikey=" 34 DATA_SOURCE += secrets['alphavantage_key'] 35 symbols = ["DJIA", "INX", "AAPL", "TSLA", "MSFT"] 36 37 # Set text, font, and color 38 group = displayio.Group() 39 symbol_text = label.Label(terminalio.FONT, text="WiFi", color=0xFFFFFF, scale=3) 40 symbol_text.anchor_point = (0.0, 0.0) 41 symbol_text.anchored_position = (0, 10) 42 43 price_text = label.Label(terminalio.FONT, text="Connect...", color=0xFFFF00, scale=3) 44 price_text.anchor_point = (0, 1) 45 price_text.anchored_position = (0, 75) 46 47 change_text = label.Label(terminalio.FONT, text="", color=0xFFFF00, scale=2) 48 change_text.anchor_point = (0, 0) 49 change_text.anchored_position = (80, 10) 50 51 group.append(symbol_text) 52 group.append(price_text) 53 group.append(change_text) 54 minitft.display.show(group) 55 56 refresh = None 57 i = 0 58 while True: 59 # only query the api every 10 sec (and on first run) 60 if (not refresh) or ((time.monotonic() - refresh) > 10): 61 try: 62 symbol = symbols[i] 63 i = (i + 1) % len(symbols) # go to the next symbol 64 response = wifi.get(DATA_SOURCE+"&symbol="+symbol).json() 65 print("Response is", response) 66 symbol_text.text = response['Global Quote']['01. symbol'] 67 spot = round(float(response['Global Quote']['05. price'])) 68 price_text.text = '${:,d}'.format(spot) 69 change = float(response['Global Quote']['09. change']) 70 print("Price is $", spot, "Change: $", change) 71 if change >= 0: 72 change_text.text = '+${:,d}'.format(round(change)) 73 change_text.color = 0x00FF00 74 else: 75 change_text.text = '-${:,d}'.format(abs(round(change))) 76 change_text.color = 0xFF0000 77 refresh = time.monotonic() 78 except RuntimeError as e: 79 print("Some error occured, retrying! -", e) 80 time.sleep(5) 81 continue 82 time.sleep(5)