crypto added

This commit is contained in:
Neythen
2021-05-14 13:02:22 +01:00
parent 5db70489b6
commit c4d0a61ec0
7 changed files with 83 additions and 54 deletions

View File

@@ -3,16 +3,17 @@ import time
import csv import csv
import pytz import pytz
from datetime import datetime from datetime import datetime
import pyEX
import datetime as dt import datetime as dt
import sys, os, base64, hashlib, hmac import sys, os, base64, hashlib, hmac
import requests import requests
from pycoingecko import CoinGeckoAPI
def readCSV(max_stocks): def readCSV(file_path, max_stocks):
symbols = [] symbols = []
stock_info = {} stock_info = {}
f = open('csv/tickers.csv', 'r') f = open(file_path, 'r')
CSV = csv.reader(f) CSV = csv.reader(f)
next(CSV) next(CSV)
i = 0 i = 0
@@ -51,7 +52,6 @@ def updateUpdate(NY_time):
def updateStockPrices(symbols): def updateStockPrices(symbols):
try: try:
quotes = [finnhubClient.quote(symbol) for symbol in symbols] quotes = [finnhubClient.quote(symbol) for symbol in symbols]
current_prices = [quote['c'] for quote in quotes] current_prices = [quote['c'] for quote in quotes]
@@ -59,10 +59,6 @@ def updateStockPrices(symbols):
print(current_prices) print(current_prices)
print(opening_prices) print(opening_prices)
print(current_prices, opening_prices) print(current_prices, opening_prices)
CSV = open('csv/tickers.csv', 'w+') CSV = open('csv/tickers.csv', 'w+')
CSV.write('name,current,opening\n') CSV.write('name,current,opening\n')
@@ -71,10 +67,8 @@ def updateStockPrices(symbols):
CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n') CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n')
CSV.close() CSV.close()
print('API called successfully') print('API called successfully')
except Exception as e: 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) print(e)
@@ -139,6 +133,18 @@ def updateStockPricesIEX(symbols):
print(lasts) print(lasts)
def updateCrypto(coins):
response = coingecko_client.get_price(ids=','.join(coins), vs_currencies = 'usd', include_24hr_change=True)
CSV = open('csv/crypto.csv', 'w+')
CSV.write('name,current,24hr change\n')
for coin in coins:
CSV.write(coin+ ',' + str(response[coin]['usd']) + ',' + str(response[coin]['usd_24h_change']) + '\n')
CSV.close()
if __name__ == '__main__': if __name__ == '__main__':
finnhubAPIkey = "c24qddqad3ickpckgg80" #Finnhub finnhubAPIkey = "c24qddqad3ickpckgg80" #Finnhub
finnhubsandboxAPIkey = "sandbox_c24qddqad3ickpckgg8g" #Finnhub finnhubsandboxAPIkey = "sandbox_c24qddqad3ickpckgg8g" #Finnhub
@@ -155,6 +161,9 @@ if __name__ == '__main__':
finnhubClient = finnhub.Client(api_key=finnhubAPIkey) finnhubClient = finnhub.Client(api_key=finnhubAPIkey)
coingecko_client = CoinGeckoAPI()
NY_zone = pytz.timezone('America/New_York') NY_zone = pytz.timezone('America/New_York')
NY_time = datetime.now(NY_zone) NY_time = datetime.now(NY_zone)
@@ -164,30 +173,29 @@ if __name__ == '__main__':
NY_time = datetime.now(NY_zone) NY_time = datetime.now(NY_zone)
print(NY_time) print(NY_time)
coins, coin_info = readCSV('csv/crypto.csv', max_stocks)
print(coins, coin_info)
updateCrypto(coins)
sys.exit()
while True: while True:
NY_time = datetime.now(NY_zone) NY_time = datetime.now(NY_zone)
symbols, stock_info = readCSV(max_stocks) symbols, stock_info = readCSV('csv/tickers.csv', max_stocks)
if opening < NY_time < closing and datetime.today().weekday() < 5: # we need to do real time updating if opening < NY_time < closing and datetime.today().weekday() < 5: # we need to do real time updating
print('market open') print('market open')
updateStockPrices(symbols) updateStockPrices(symbols)
updateUpdate(NY_time) updateUpdate(NY_time)
elif emptyInfo(symbols, stock_info): # if theres any empty stocks elif emptyInfo(symbols, stock_info): # if theres any empty stocks
updateStockPrices(symbols) updateStockPrices(symbols)
updateUpdate(NY_time) updateUpdate(NY_time)
else: else:
# update if last update was before the previous days closing # update if last update was before the previous days closing
f = open('csv/last_update.csv', 'r') f = open('csv/last_update.csv', 'r')
CSV = csv.reader(f) CSV = csv.reader(f)
last_update_str = next(CSV)[0] last_update_str = next(CSV)[0]

BIN
final.ppm

Binary file not shown.

Binary file not shown.

View File

@@ -17,6 +17,7 @@ import pexpect
from rgbmatrix import RGBMatrix, RGBMatrixOptions from rgbmatrix import RGBMatrix, RGBMatrixOptions
from rgbmatrix.graphics import * from rgbmatrix.graphics import *
def getInput(Block=False): def getInput(Block=False):
if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
msg = sys.stdin.read(1) msg = sys.stdin.read(1)
@@ -118,8 +119,6 @@ class StockTicker():
while offset_x > -img_width: while offset_x > -img_width:
offset_x -= 1 offset_x -= 1
self.setImage(image1, offset_x = offset_x, offset_y = offset_y) self.setImage(image1, offset_x = offset_x, offset_y = offset_y)
@@ -129,8 +128,6 @@ class StockTicker():
time.sleep(self.delay) time.sleep(self.delay)
try: try:
msg = getInput() msg = getInput()
if msg == 'K': if msg == 'K':
@@ -139,8 +136,6 @@ class StockTicker():
break break
self.process_msg(msg) self.process_msg(msg)
except KeyboardInterrupt: except KeyboardInterrupt:
sys.stdout.flush() sys.stdout.flush()
pass pass
@@ -288,6 +283,32 @@ class StockTicker():
image_list.append(self.blank) image_list.append(self.blank)
image_list.append(stitchedStock) image_list.append(stitchedStock)
for i, coin in enumerate(self.coins):
info = self.coin_info[coin]
change = float(info[1]) #TEXT
ticker = coin #TEXT
current = '%.2f' % float(info[0]) #TEXT
arrow, change = self.getArrow(change)
change = '%.2f' % change
midFrame = self.textToImage(ticker, current, change, arrow) #IMAGE THE TEXT
try:
logos_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos')
print(os.path.join(logos_path, ticker + '.png'))
logo = Image.open(os.path.join(logos_path, ticker + '.png'))
stitchedStock = self.stitchImage([logo,midFrame])
except:
print('no logo for ' + ticker)
stitchedStock = midFrame
image_list.append(self.blank)
image_list.append(stitchedStock)
finalDisplayImage = self.stitchImage(image_list) finalDisplayImage = self.stitchImage(image_list)
if updated_img == 1: if updated_img == 1:
@@ -321,7 +342,23 @@ class StockTicker():
f.close() f.close()
print(self.symbols) self.coins = []
self.coin_info = {}
f = open('csv/crypto.csv', 'r')
CSV = csv.reader(f)
next(CSV)
for row in CSV:
print(row)
try:
coin, current_price, day_change = row
self.coins.append(coin)
self.coin_info[coin] = [current_price, day_change]
except:
symbol = row[0]
self.coins.append(coin)
self.coin_info[coin] = []
f.close()
#Main run definition called by server #Main run definition called by server
def runStockTicker(self, runtime, delay, speedtime): def runStockTicker(self, runtime, delay, speedtime):
@@ -390,7 +427,8 @@ if __name__ == '__main__':
#stock_ticker.displayText() #stock_ticker.displayText()
#stock_ticker.displayStocks() stock_ticker.getFullStockImage(1)
stock_ticker.displayStocks()

27
test.py
View File

@@ -11,31 +11,14 @@ from stockTicker import StockTicker
import finnhub import finnhub
import pexpect import pexpect
from pycoingecko import CoinGeckoAPI
if __name__ == '__main__': if __name__ == '__main__':
#stock_ticker = StockTicker()
SandboxApiKey = "sandbox_c24qddqad3ickpckgg8g"
ApiKey = "c24qddqad3ickpckgg80"
#stock_ticker.runStockTicker('', 1, 1) cg = CoinGeckoAPI()
#stock_ticker.GetSymbols()
#stock_ticker.GetfullStockImage() print(cg.get_price(ids='bitcoin, ethereum', vs_currencies = 'usd', include_24hr_change=True))
#stock_ticker.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.02)
print('hello')
child = pexpect.spawn("sudo -E python3 stockTicker.py")
time.sleep(3)
child.sendline('R')
print('sent stocks')
time.sleep(3)
child.sendline('K')
print('sent kill')
time.sleep(3)
#time.sleep(3)
#child.sendline('stop')
#print('sent stop')
#stock_ticker.displayMatrix()