Open muhammedimad opened 5 years ago
The code functions
import requests
import sqlite3
import sys
A function that connects a local database to Python
def connect(): database = sqlite3.connect('testDatabase.db',isolation_level=None,timeout=10) return database
This function receives a stock symbol and fetch its information.
def fetch_stock(symbol): url = "https://sandbox.iexapis.com/stable/stock/"+str(symbol)+"/quote?token=Tpk_087a52e2547e449e9cee8748f00491eb" response=requests.get(url) if (response.status_code)==404: return 0 else: dataset = response.json() return (dataset)
A function to check if the stock is already cached in the database.
def is_cached(ssymbol,database): c1 = database.cursor() res = list(c1.execute('''select symbol from stocks ''')) res=flatter(res) if ssymbol in res: return True else: return False
The main function that adds the stock to the database if it's not cached.
def add_stock_to_db(symbol,database): if is_cached(symbol.upper(),database) is True:
sys.exit()
else:
stock_data=fetch_stock(symbol)
if stock_data==0:
exit(0)
else :
c1 = database.cursor()
c1.execute("INSERT INTO stocks VALUES (?,?)", [stock_data["symbol"], stock_data["companyName"]])
> A complementary function that refines a dictionary.
def flatter(tu): l = [] for i in tu: l.append(i[0]) return l
stocksDatabase=connect() add_stock_to_db('gold',stocksDatabase)
Case 1: searching for an already cached stock
Case 2: searching for uncached stock and caching it.
Case 3: Trying to search for a non-existing stock.
The aim is to find a way to check for the existence of stock in the database, to help in search features and other features.