Skip to content

Commit

Permalink
♻️ Cleaning up code to adhere to flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
Paulinakhew committed Dec 5, 2019
1 parent fdef74e commit c8034b8
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 50 deletions.
131 changes: 81 additions & 50 deletions model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import requests
import datetime

from unittest.mock import MagicMock # this will be used after modularization
# from unittest.mock import MagicMock # this will be used after modularization


def current_user():
'''Selects the username of the current user from the current_user db'''
Expand All @@ -17,7 +18,8 @@ def current_user():

return username[0]

def log_in(user_name,password):

def log_in(user_name, password):
'''Logs the user in if they exist in the user db
Parameters:
Expand Down Expand Up @@ -45,8 +47,9 @@ def log_in(user_name,password):
cursor.close()
connection.close()

def create_(new_user,new_password,new_fund):
connection = sqlite3.connect('trade_information.db',check_same_thread=False)

def create_(new_user, new_password, new_fund):
connection = sqlite3.connect('trade_information.db', check_same_thread=False)
cursor = connection.cursor()

try:
Expand All @@ -69,6 +72,7 @@ def create_(new_user,new_password,new_fund):
cursor.close()
connection.close()


def update_holdings():
connection = sqlite3.connect('trade_information.db', check_same_thread=False)
cursor = connection.cursor()
Expand All @@ -78,12 +82,13 @@ def update_holdings():
cursor.close()
connection.close()


def sell(username, ticker_symbol, trade_volume):
#we have to search for how many of the stock we have
#compare trade volume with how much stock we have
#if trade_volume <= our stock, proceed
#else return to menu
#we need a database to save how much money we have and how much stock
# we have to search for how many of the stock we have
# compare trade volume with how much stock we have
# if trade_volume <= our stock, proceed
# else return to menu
# we need a database to save how much money we have and how much stock
username = current_user()
database = 'trade_information.db'
connection = sqlite3.connect(database, check_same_thread=False)
Expand All @@ -110,17 +115,19 @@ def sell(username, ticker_symbol, trade_volume):
return False, return_list
#if yes return new balance = current balance - transaction cost


def calculate_transaction_revenue(trade_volume, last_price, brokerage_fee):
transaction_revenue = (trade_volume * last_price) - brokerage_fee

return transaction_revenue


def sell_db(return_list):
# return_list = (last_price, brokerage_fee, current_balance, trade_volume, agg_balance, username, ticker_symbol, current_number_shares)
#check if user holds enough stock
#update user's balance
#insert transaction
#if user sold all stocks holdings row should be deleted not set to 0
# check if user holds enough stock
# update user's balance
# insert transaction
# if user sold all stocks holdings row should be deleted not set to 0
database = 'trade_information.db'
connection = sqlite3.connect(database,check_same_thread = False)
cursor = connection.cursor()
Expand All @@ -144,7 +151,7 @@ def sell_db(return_list):
""".format(agg_balance, username)
)

#transactions
# transactions
cursor.execute("""
INSERT INTO transactions(
ticker_symbol,
Expand All @@ -157,9 +164,9 @@ def sell_db(return_list):
);""".format(ticker_symbol, trade_volume*-1, username, last_price, date)
)

#holdings
#at this point, it it assumed that the user has enough shares to sell.
if current_number_shares >= trade_volume: #if user isn't selling all shares of a specific company
# holdings
# at this point, it it assumed that the user has enough shares to sell.
if current_number_shares >= trade_volume: # if user isn't selling all shares of a specific company
tot_shares = float(current_number_shares)-float(trade_volume)
cursor.execute('''
UPDATE holdings
Expand All @@ -172,33 +179,37 @@ def sell_db(return_list):
cursor.close()
connection.close()


def buy(username, ticker_symbol, trade_volume):
#we need to return True or False for the confirmation message
# we need to return True or False for the confirmation message
trade_volume = float(trade_volume)
last_price = float(quote_last_price(ticker_symbol))
brokerage_fee = 6.95 #TODO: un-hardcode this value
brokerage_fee = 6.95 # TODO: un-hardcode this value
username = current_user()
current_balance = get_user_balance(username)
transaction_cost = calculate_transaction_cost(trade_volume, last_price, brokerage_fee)
left_over = float(current_balance) - float(transaction_cost)
return_list = (last_price, brokerage_fee, current_balance, trade_volume,left_over,username,ticker_symbol)
return_list = (last_price, brokerage_fee, current_balance, trade_volume, left_over, username, ticker_symbol)
if transaction_cost <= current_balance:
return True, return_list #success
return True, return_list # success
else:
return False, return_list
#if yes return new balance = current balance - transaction cost
# if yes return new balance = current balance - transaction cost


def calculate_transaction_cost(trade_volume, last_price, brokerage_fee):
transaction_cost = (trade_volume * last_price) + brokerage_fee

return transaction_cost

def buy_db(return_list): # return_list = (last_price, brokerage_fee, current_balance, trade_volume, left_over, username, ticker_symbol)
connection = sqlite3.connect('trade_information.db',check_same_thread=False)

def buy_db(return_list):
# return_list = (last_price, brokerage_fee, current_balance, trade_volume, left_over, username, ticker_symbol)
connection = sqlite3.connect('trade_information.db', check_same_thread=False)
cursor = connection.cursor()
database = 'trade_information.db'
username = current_user()
connection = sqlite3.connect(database,check_same_thread = False)
connection = sqlite3.connect(database, check_same_thread=False)
cursor = connection.cursor()
last_price = return_list[0]
# brokerage_fee = return_list[1]
Expand All @@ -210,16 +221,16 @@ def buy_db(return_list): # return_list = (last_price, brokerage_fee, current_bal
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d %I:%M %p")

#update users(current_balance), stocks, holdings.
#users
#updating the balance of the user
# update users(current_balance), stocks, holdings.
# users
# updating the balance of the user
cursor.execute("""
UPDATE user
SET current_balance = {}
WHERE username = '{}';
""".format(left_over, username)
)
#transactions
# transactions
cursor.execute("""
INSERT INTO transactions(
ticker_symbol,
Expand All @@ -229,15 +240,24 @@ def buy_db(return_list): # return_list = (last_price, brokerage_fee, current_bal
date
) VALUES(
'{}',{},'{}',{},'{}'
);""".format(ticker_symbol,trade_volume,username,last_price,date)
);""".format(
ticker_symbol,
trade_volume,
username,
last_price,
date
)
)

#inserting information
#holdings
query = 'SELECT count(*), num_shares FROM holdings WHERE username = "{}" AND ticker_symbol = "{}"'.format(username, ticker_symbol)
# inserting information
# holdings
query = 'SELECT count(*), num_shares FROM holdings WHERE username = "{}" AND ticker_symbol = "{}"'.format(
username,
ticker_symbol
)
cursor.execute(query)
fetch_result = cursor.fetchone()
if fetch_result[0] == 0: #if the user didn't own the specific stock
if fetch_result[0] == 0: # if the user didn't own the specific stock
cursor.execute('''
INSERT INTO holdings(last_price, num_shares, ticker_symbol, username)
VALUES (
Expand All @@ -256,30 +276,34 @@ def buy_db(return_list): # return_list = (last_price, brokerage_fee, current_bal
cursor.close()
connection.close()


def get_user_balance(username):
username = current_user()
connection = sqlite3.connect('trade_information.db', check_same_thread = False)
connection = sqlite3.connect('trade_information.db', check_same_thread=False)
cursor = connection.cursor()
query = 'SELECT current_balance FROM user WHERE username = "{}";'.format(username)
cursor.execute(query)
fetched_result = cursor.fetchone()
cursor.close()
connection.close()
return fetched_result[0] #cursor.fetchone() returns tuples
return fetched_result[0] # cursor.fetchone() returns tuples


def lookup_ticker_symbol(company_name):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input='+company_name
#FIXME The following return statement assumes that only one
#ticker symbol will be matched with the user's input.
#FIXME There also isn't any error handling.
# FIXME: The following return statement assumes that only one
# ticker symbol will be matched with the user's input.
# FIXME: There also isn't any error handling.
return json.loads(requests.get(endpoint).text)[0]['Symbol']


def quote_last_price(ticker_symbol):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol='+ticker_symbol
return json.loads(requests.get(endpoint).text)['LastPrice']


def display_user_holdings():
username=current_user()
username = current_user()
connection = sqlite3.connect("trade_information.db", check_same_thread=False)
cursor = connection.cursor()
cursor.execute("SELECT ticker_symbol,num_shares,last_price FROM holdings WHERE username='{}';".format(username))
Expand All @@ -288,8 +312,9 @@ def display_user_holdings():
connection.close()
return user_holdings


def display_user_transactions():
username=current_user()
username = current_user()
connection = sqlite3.connect("trade_information.db", check_same_thread=False)
cursor = connection.cursor()
cursor.execute("SELECT ticker_symbol,num_shares,last_price,date FROM transactions WHERE owner_username='{}';".format(username))
Expand All @@ -298,6 +323,7 @@ def display_user_transactions():
connection.close()
return user_transactions


def get_users_with_holdings():
connection = sqlite3.connect("trade_information.db", check_same_thread=False)
cursor = connection.cursor()
Expand All @@ -308,6 +334,7 @@ def get_users_with_holdings():
connection.close()
return users_list


def get_tkr_symb_from_holdings():
connection = sqlite3.connect("trade_information.db", check_same_thread=False)
cursor = connection.cursor()
Expand All @@ -318,6 +345,7 @@ def get_tkr_symb_from_holdings():
connection.close()
return symbols_list


def update_leaderboard():
connection = sqlite3.connect('trade_information.db',check_same_thread=False)
cursor = connection.cursor()
Expand All @@ -336,27 +364,30 @@ def update_leaderboard():
cursor.close()
connection.close()


def log_out():
connection = sqlite3.connect('trade_information.db',check_same_thread=False)
cursor = connection.cursor()

cursor.execute(
"""REPLACE INTO current_user(
pk,
username
) VALUES(
1,
'{}'
);""".format(
'randomuser'
)
"""REPLACE INTO current_user(
pk,
username
) VALUES(
1,
'{}'
);""".format(
'randomuser'
)
)
connection.commit()
cursor.close()
connection.close()


def test_calculate_transaction_cost():
assert calculate_transaction_cost(1, 50, 7) == 57


def test_calculate_transaction_revenue():
assert calculate_transaction_revenue(1, 50, 7) == 43
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[flake8]

max-line-length = 127

0 comments on commit c8034b8

Please sign in to comment.