farjun / RailsStockProject

python django project for trading platform
1 stars 1 forks source link

Caching -non existing- stock in the database #16

Open muhammedimad opened 5 years ago

muhammedimad commented 5 years ago

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.

muhammedimad commented 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)

muhammedimad commented 5 years ago

Case 1: searching for an already cached stock

Screen Shot 2019-10-11 at 14 17 34
muhammedimad commented 5 years ago

Case 2: searching for uncached stock and caching it.

Screen Shot 2019-10-11 at 14 26 01
muhammedimad commented 5 years ago

Case 3: Trying to search for a non-existing stock.

Screen Shot 2019-10-11 at 14 28 08