finnhub api added, running va server leads to a crash

This commit is contained in:
Neythen 2021-04-28 20:39:30 +01:00
parent df0735c6b5
commit 00bf284d33
7 changed files with 55 additions and 22 deletions

View File

@ -1,2 +1,5 @@
# fintic # fintic
To conver bdf font to pil format do pilfont.py <font filename> To conver bdf font to pil format do pilfont.py <font filename>
pip3 install finnhub-python

BIN
final.ppm Normal file → Executable file

Binary file not shown.

View File

@ -128,7 +128,8 @@ def matrix():
global LastCommand global LastCommand
if "Run Display" in request.form: if "Run Display" in request.form:
pass pass
stock_ticker.runStockTicker(command, DelayTime, speedTime) #stock_ticker.runStockTicker(command, DelayTime, speedTime)
stock_ticker.displayMatrix()
LastCommand = 'Run display' LastCommand = 'Run display'
elif "Stop Display (at next refresh)" in request.form: elif "Stop Display (at next refresh)" in request.form:
pass pass

View File

@ -5,23 +5,26 @@
# stockTicker can not be copied and/or distributed without the express # stockTicker can not be copied and/or distributed without the express
# permission of Daniel Richardson # permission of Daniel Richardson
from twelvedata import TDClient
import sys import sys
import os import os
import threading import threading
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
import time import time
import csv import csv
import requests
from rgbmatrix import RGBMatrix, RGBMatrixOptions from rgbmatrix import RGBMatrix, RGBMatrixOptions
import finnhub
class StockTicker(): class StockTicker():
def __init__(self): def __init__(self):
#Define global resources #Define global resources
self.symbols = [] self.symbols = []
#self.ApiKeys = [["b1be6696d54342bdb5c8f59a052854fd","237d183faf984e7eba708a647c55153a","3012b3cb19784ed4be2b02e9907e53cb"],["f835e85df2a74df1904fe6dc53bcc17a","41ec268496744c34a96e3c408081300b","2d566fc71ade46d688713b13730c5219"]] #self.ApiKeys = [["b1be6696d54342bdb5c8f59a052854fd","237d183faf984e7eba708a647c55153a","3012b3cb19784ed4be2b02e9907e53cb"],["f835e85df2a74df1904fe6dc53bcc17a","41ec268496744c34a96e3c408081300b","2d566fc71ade46d688713b13730c5219"]]
self.ApiKeys = [["6172b84d1f464ad88b95ed52e4391bce","979f9b8c9ee748fbbb57cb490ccaaf42","593fa818a44144699b75433aafd92d15"]] #self.ApiKeys = [["6172b84d1f464ad88b95ed52e4391bce","979f9b8c9ee748fbbb57cb490ccaaf42","593fa818a44144699b75433aafd92d15"]]
self.ApiKey = "c24qddqad3ickpckgg80"
self.SandboxApiKey = "sandbox_c24qddqad3ickpckgg8g"
self.retrievedList = [] self.retrievedList = []
self.greenORred = (255, 255, 255) self.greenORred = (255, 255, 255)
self.ListStocks = [] self.ListStocks = []
@ -43,8 +46,9 @@ class StockTicker():
options.chain_length = 1 options.chain_length = 1
options.parallel = 1 options.parallel = 1
options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat' options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat'
options.gpio_slowdown = 4 options.gpio_slowdown = 3
self.matrix = RGBMatrix(options = options) self.matrix = RGBMatrix(options = options)
self.finnhubClient = finnhub.Client(api_key=self.SandboxApiKey)
def openImage(self, image_file): def openImage(self, image_file):
image = Image.open(image_file) image = Image.open(image_file)
@ -67,6 +71,8 @@ class StockTicker():
#however it's super fast and seems to work fine #however it's super fast and seems to work fine
#https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4 #https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4
img_width, img_height = image.size img_width, img_height = image.size
print('args', img_width, img_height, offset_x, offset_y, image)
self.matrix.SetPixelsPillow(offset_x, offset_y, img_width, img_height, image) self.matrix.SetPixelsPillow(offset_x, offset_y, img_width, img_height, image)
else: else:
# First implementation of a SetImage(). OPTIMIZE_ME: A more native # First implementation of a SetImage(). OPTIMIZE_ME: A more native
@ -104,6 +110,8 @@ class StockTicker():
img_width, img_height = image.size img_width, img_height = image.size
print('hw', img_width, img_height)
print(offset_x, offset_y) print(offset_x, offset_y)
while offset_x > -img_width: while offset_x > -img_width:
@ -165,7 +173,7 @@ class StockTicker():
img = Image.new('RGB', (150, 32)) img = Image.new('RGB', (150, 32))
d = ImageDraw.Draw(img) d = ImageDraw.Draw(img)
d.text((4, -4), TICKER, fill=(255, 255, 255), font=font) d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 13), CURRENT, fill=self.greenORred, font=font) d.text((4, 13), CURRENT, fill=self.greenORred, font=font)
text_width_current, text_height = self.get_text_dimensions(CURRENT, font) text_width_current, text_height = self.get_text_dimensions(CURRENT, font)
@ -187,7 +195,7 @@ class StockTicker():
max_height = max(heights) max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height)) new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0 x_offset = 0
for im in IMAGES[0:2]: for im in IMAGES:
new_im.paste(im, (x_offset,0)) new_im.paste(im, (x_offset,0))
x_offset += im.size[0] x_offset += im.size[0]
return new_im return new_im
@ -198,10 +206,21 @@ class StockTicker():
return 0 return 0
#Get current prices and day prices for the ticker then format the response into an array #Get current prices and day prices for the ticker then format the response into an array
def getStockPrices(self, APIKEY, SYMBOLS): def getStockPrices(self, SYMBOLS):
APIKEY = "237d183faf984e7eba708a647c55153a"
try: try:
symbols_list = SYMBOLS.split(",") symbols_list = SYMBOLS.split(",")
quotes = [self.finnhubClient.quote(symbol) for symbol in symbols_list]
current_prices = [quote['c'] for quote in quotes]
opening_prices = [quote['o'] for quote in quotes]
for i, symbol in enumerate(symbols_list):
self.retrievedList.append([symbol, current_prices[i], opening_prices[i]])
print(self.retrievedList)
'''
td = TDClient(apikey=APIKEY) td = TDClient(apikey=APIKEY)
tmin = td.time_series(symbol=SYMBOLS, interval="1min", outputsize='1').as_json() tmin = td.time_series(symbol=SYMBOLS, interval="1min", outputsize='1').as_json()
tday = td.time_series(symbol=SYMBOLS, interval="1day", outputsize='2').as_json() tday = td.time_series(symbol=SYMBOLS, interval="1day", outputsize='2').as_json()
@ -215,9 +234,12 @@ class StockTicker():
self.retrievedList[i].append(symbols_list[i]) self.retrievedList[i].append(symbols_list[i])
self.retrievedList[i].append(currentMinPriceClose) self.retrievedList[i].append(currentMinPriceClose)
self.retrievedList[i].append(currentDayPriceClose) self.retrievedList[i].append(currentDayPriceClose)
except: '''
self.ApiCalledError = True except Exception as e:
print("Could not fetch data - API CALLS REACHED? - Will display old image") print("Could not fetch data - API CALLS REACHED? - Will display old image")
print(e)
self.ApiCalledError = True
#Connect all the pieces togeather creating 1 long final stock image #Connect all the pieces togeather creating 1 long final stock image
def GetfullStockImage(self): def GetfullStockImage(self):
@ -229,9 +251,9 @@ class StockTicker():
print('elapsed time: ' + str((time.time()-start))) print('elapsed time: ' + str((time.time()-start)))
j=0 j=0
while (j<3): while (j<3):
print('API KEY: ' + str(self.ApiKeys[self.keySwapper][j]))
# NT: this weird API key thing doesnt work, when I hard code the API key in the above function it does # NT: this weird API key thing doesnt work, when I hard code the API key in the above function it does
self.getStockPrices(self.ApiKeys[self.keySwapper][j], self.symbols[(j+self.parseCSV)][0]) self.getStockPrices(self.symbols[(j+self.parseCSV)][0])
if (self.ApiCalledError == False): if (self.ApiCalledError == False):
j+=1 j+=1
@ -250,6 +272,7 @@ class StockTicker():
StitchedStock = self.stitchImage([Logo,MidFrame]) StitchedStock = self.stitchImage([Logo,MidFrame])
self.ListStocks.append(self.blank) self.ListStocks.append(self.blank)
self.ListStocks.append(StitchedStock) self.ListStocks.append(StitchedStock)
self.retrievedList = [] self.retrievedList = []
else: else:
break break
@ -263,8 +286,8 @@ class StockTicker():
#Send the final stitched image to the display for set amount of time #Send the final stitched image to the display for set amount of time
def displayMatrix(self): def displayMatrix(self):
#os.system("sudo ./demo -D1 final.ppm -t " + str(displayTime) +" -m "+ str(speedDisplay) +" --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256") #os.system("sudo ./demo -D1 final.ppm -t " + str(displayTime) +" -m "+ str(speedDisplay) +" --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256")
os.system("sudo ./demo -D1 final.ppm -t " + str(self.displayTime) +" -m "+ str(self.speedDisplay) +" --led-gpio-mapping=adafruit-hat --led-rows=64 --led-cols=64 --led-slowdown-gpio=4 ") #os.system("sudo ./demo -D1 final.ppm -t " + str(self.displayTime) +" -m "+ str(self.speedDisplay) +" --led-gpio-mapping=adafruit-hat --led-rows=64 --led-cols=64 --led-slowdown-gpio=4 ")
self.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.05)
#Retrieve symbols from the CSV file #Retrieve symbols from the CSV file
def GetSymbols(self): def GetSymbols(self):
@ -297,9 +320,9 @@ class StockTicker():
if (self.running == True): if (self.running == True):
if (self.keySwapper<=1): if (self.keySwapper<=1):
if(self.parseCSV <= self.symbolLength): if(self.parseCSV <= self.symbolLength):
th = threading.Thread(target=self.displayMatrix) #th = threading.Thread(target=self.displayMatrix)
th.start() #th.start()
#displayMatrix() self.displayMatrix()
time.sleep((int(self.displayTime) - int(self.Delay))) time.sleep((int(self.displayTime) - int(self.Delay)))
self.GetfullStockImage() self.GetfullStockImage()
self.keySwapper += 1 self.keySwapper += 1

Binary file not shown.

12
test.py
View File

@ -8,12 +8,18 @@ import csv
from rgbmatrix import RGBMatrix, RGBMatrixOptions from rgbmatrix import RGBMatrix, RGBMatrixOptions
from stockTicker import StockTicker from stockTicker import StockTicker
import finnhub
if __name__ == '__main__': if __name__ == '__main__':
stock_ticker = StockTicker() stock_ticker = StockTicker()
SandboxApiKey = "sandbox_c24qddqad3ickpckgg8g"
ApiKey = "c24qddqad3ickpckgg80"
stock_ticker.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.005)
#stock_ticker.runStockTicker('', 1, 1)
stock_ticker.GetSymbols()
stock_ticker.GetfullStockImage()
stock_ticker.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.02)