def quote(ticker): with Markit(ticker) as m: try: price = m.quote() quota = ticker + " price = $" + str(price) return price except: print("\nDid not find ticker") return 0
def get_data(): markit = Markit() try: name = (markit.get_quote_msft())["Name"] except: pass try: last_price = (markit.get_quote_msft())["LastPrice"] except: pass try: timestamp = (markit.get_quote_msft())["Timestamp"] except: pass try: name1 = (markit.get_quote_goog())["Name"] except: pass try: last_price1 = (markit.get_quote_goog())["LastPrice"] except: pass try: timestamp1 = (markit.get_quote_goog())["Timestamp"] except: pass try: ORM.update_goog(name1, last_price1, timestamp1) except: pass try: ORM.update_msft(name, last_price, timestamp) except: pass sleep(5) get_data()
def buy_stocks(username,shares,password,stock_exchange, stock_symbol,volume,stock_price): orm.check_balance(username) for cash in balance: if cash[balance'] == '0': print("insufficient balance") if balance > (shares * stock_price): orm.buying_stocks(username,password,stock_exchange, stock_symbol,volume,stock_price) def buying_stocks(check_balance, stock_exchange, stock_symbol, stock_price, volume, username,password): #Check the balance print("\n\nTo access any function below, enter the corresponding key") print ('''To: want to buy stocks,press A. check Balance, press B. deposit cash, press D. exit service, press E\n :''') status = input("") if status == 'A': passcheck(get_password,username) check_balance(balance) if status=='B': check_balance = orm.get_balance(username) elif status=='D': passcheck(get_password,username) depositcash(stock_price*stock_symbol) elif status=='E': print ("Thank you for using our Services") # if enough balance, buy stocks, else return insufficient funds def buy(check_balance,shares,stock_price): number_of_shares = input("Enter number of shares: ") object = Markit() price = object.get_quote(stock_symbol) enter_price = input("Enter the price to purchase shares: ") if get_stock(stock) == None: stock_to_buy = {} stock_to_buy['shares'] = shares stock_to_buy['value'] = "{0:.2f}".format(float(stock_price)) else: stock_to_buy = get_stock(stock) stock_to_buy['value'] = "{0:.2f}".format(float(enter_price) * int(number_of_shares)) stock_to_buy['shares'] = str(int(stock_to_buy['shares']) + int(shares)) #return "Your balance is " + ({0:.2f}".format(float(enter_price) * int(number_of_shares) - balance) def check_balance(username): balance = ORM.check_balance(username) return balance ''' pass def sell_stocks(shares, price): sale_price = input("Enter sale price: ") for stock in portfolio: if stock['portfolio'] portfolio.remove(stock) pass ''' if __name__ == '__main__': buy_stocks(username,shares,password,stock_exchange, stock_symbol,volume,stock_price)
def retrieve_company_data(stock_symbol): object = Markit() companyquote = object.get_quote(stock_symbol) return(companyquote)
def retrive_symbols(stock_symbol): object = Markit() companylist = pd.DataFrame.from_dict(object.company_search(stock_symbol)) return(companylist)
def quote(ticker_symbol): with Markit() as m: return m.quote(ticker_symbol)
def lookup(company_name): #endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input='+company_name #response = json.loads(requests.get(endpoint).text) #return response[0]['Symbol'] with Markit() as m: return m.lookup(company_name)
def __init__(self): self.view = View() self.db = TradingUserDB() self.api = Markit()
class controller: def __init__(self): self.m = Markit() self.l = model() def get_tickersymbol(self, string): c = self.m.company_search(string) q = c[0]['Symbol'] return q def get_marketdata(self, string): m = self.m.get_quote(string) return m def new_account(self, string1, string2, string3): name = string1 user_name = string2 password = string3 self.l.add_user(name, user_name, password) def check_account(self, str1, str2): chk = self.l.check_user(str1, str2) return chk def buy(self, a, q, usr, sy): total_price = a['LastPrice'] * q now = self.l.see_earning(usr) if total_price < now[0]: ch = self.l.see_quant(usr, sy) if (ch == None): self.l.add_stock(a, usr, q) balance = now[0] - total_price self.l.balance_update(balance, usr) else: nq = q + ch[0] balance = now[0] - total_price self.l.balance_update(balance, usr) self.l.quant_update(nq, usr, sy) print("\n...The Transaction was Successfull...") print("Balance:", balance) else: print("\nYou dont have enough fund to buy") def sell(self, dt, quant, usr_n, sn): wr = self.l.check_stock(usr_n, sn) if (wr != None): g_price = dt['LastPrice'] * quant rnow = self.l.see_earning(usr_n) n_price = g_price + rnow[0] self.l.balance_update(n_price, usr_n) rq = self.l.see_quant(usr_n, sn) lq = rq[0] - quant if (lq == 0): self.l.remove_stock(usr_n, sn) print("\n.....The Transaction was Sucessfull.....") print("Balance:", n_price) elif (lq < 0): print("\nYou dont have this much quantity to sell") else: self.l.quant_update(lq, usr_n, sn) print("\n.....The Transaction was Sucessfull.....") print("Balance:", n_price) else: print("\nThis company is not in your list") def portfolio(self, n): b = self.l.see_stock(n) print("\nStocks:", b) k = self.l.see_earning(n) print("Earnings:", k[0]) def admin_leader(self): sl = [] pm = [] rp = [] ew = [] tr = [] net_w = [] rt = [] fd = [] di = {} ut = self.l.leaderboard() for i in ut: sl.append(i[0]) for k in sl: try: uy = self.l.only_user(k) tr.append(uy[0]) except TypeError: pass for i in tr: eh = self.l.only_quant(i) for d in eh: pm.append(d[0]) for t in tr: ej = self.l.only_symbol(t) for o in ej: rp.append(o[0]) for r in range(len(pm)): quan = pm[r] symbol = rp[r] bv = self.l.get_usr(quan, symbol) fd.append(bv[0]) gt = self.l.see_earning(bv[0]) time.sleep(3) pl = self.m.get_quote(symbol) time.sleep(3) stock_value = pl['LastPrice'] * quan net_worth = gt[0] + stock_value net_w.append(net_worth) qa = zip(fd, net_w) rt = list(qa) for each in rt: if each[0] in di: di[each[0]] = di[each[0]] + each[1] else: di[each[0]] = each[1] sorted_x = sorted(di.items(), key=operator.itemgetter(1), reverse=True) print("\n.........LeaderBoard............\n") t = PrettyTable(("Username", "Earnings")) for o in sorted_x: t.add_row(o) print(t) def user_valid(self, op): qr = self.l.username_check(op) return qr
def lookup(company_name): with Markit(company_name) as m: return m.lookup()
def __init__(self): self.api = Markit()
class TradingUserDB: def __init__(self): self.api = Markit() def signin(self, name, password): user = c.execute("SELECT id, permission_level FROM users WHERE username=(?) and password=(?)", (name, password)) user = c.fetchone() return user def user_id_check(self, user_name): c.execute("SELECT id FROM users WHERE username=(?)", (user_name,)) account = c.fetchone() return account def add_user(self, user): c.execute("INSERT INTO users(username, password, name, permission_level) VALUES(?,?,?,?)", (user.username, user.password, user.name, user.permission_level)) conn.commit() def add_account(self, account): c.execute("INSERT INTO accounts(user_id, account_number, balance) VALUES(?,?,?)", (account.user_id, account.account_number, account.balance)) conn.commit() def get_account_balance(self, id): c.execute("SELECT balance FROM accounts WHERE user_id=(?)", (id)) balance = c.fetchone() return balance def update_account(self, change, user_id): c.execute("UPDATE accounts SET balance=balance+(?) WHERE user_id=(?)", (change, user_id)) conn.commit() def get_all_user_accounts(self): c.execute("SELECT * FROM users INNER JOIN accounts ON users.id=accounts.user_id") accounts = c.fetchall() return accounts def add_to_portfolio(self, user_name, symbol, price, quantity): c.execute("INSERT INTO portfolios(user_id, symbol, price, quantity) VALUES(?,?,?,?)", (user_name, symbol, price, quantity)) conn.commit() def update_portfolio(self, portfolio_id, user_id, number_of_stocks): c.execute("UPDATE portfolios SET quantity=quantity-(?) WHERE id=(?) and user_id=(?)", (number_of_stocks, portfolio_id, user_id)) conn.commit() def remove_zero_stocks(self): c.execute("DELETE FROM portfolios WHERE quantity=(?)", (0,)) conn.commit() def subtract_stocks(self, number_of_stocks, stocks_with_symbol): price_paid = 0 while number_of_stocks > 0: for row in stocks_with_symbol: if number_of_stocks > int(row[4]): number_of_stocks -= int(row[4]) price_paid += row[3] * int(row[4]) self.update_portfolio(row[0], row[1], int(row[4])) else: self.update_portfolio(row[0], row[1], number_of_stocks) price_paid += row[3] * number_of_stocks number_of_stocks = 0 return price_paid def get_all_portfolios(self): c.execute("SELECT * FROM portfolios") portfolios = c.fetchall() return portfolios def get_own_portfolio(self, user_id): c.execute("SELECT * FROM portfolios WHERE user_id=(?)", (user_id,)) portfolio = c.fetchall() return portfolio def get_from_portfolio(self, symbol, user_id): c.execute("SELECT * FROM portfolios WHERE symbol=(?) and user_id=(?)", (symbol, user_id)) portfolios = c.fetchall() return portfolios def get_number_of_stocks_available(self, symbol, user_id): c.execute("SELECT sum(quantity) FROM portfolios WHERE symbol=(?) and user_id=(?)", (symbol, user_id)) portfolios = c.fetchall() return portfolios def current_portfolio_value(self, portfolio): value = 0.0 paid = 0.0 for row in portfolio: value += self.api.get_quote(row[2]) * float(row[4]) paid += row[3] * float(row[4]) profit = value - paid return value, paid, profit def one_portfolio_value(self, portfolio): value = 0.0 paid = 0.0 value += self.api.get_quote(portfolio[2]) * float(portfolio[4]) paid += portfolio[3] * float(portfolio[4]) profit = value - paid return value, paid, profit
#!/usr/bin/env python3 from wrapper import Markit #Markit.get_symbol() Markit.get_quote()
def __init__(self): self.m = Markit() self.l = model()
def retrieve_quote(ticker_symbol): markit_object = Markit() quote_data = markit_object.get_quote(ticker_symbol) return quote_data
class TraderController: def __init__(self): self.view = View() self.db = TradingUserDB() self.api = Markit() def login(self): user_name = self.view.get_username() password = self.view.get_password() return user_name, password def get_id(self, user_name): user_id = self.db.user_id_check(user_name) return user_id[0] def create_account(self): self.view.creating_account() user_name, password = self.login() user_id = self.db.user_id_check(user_name) if user_id == None: name = self.view.get_fullname() new_user = Player(user_name, password, name) self.db.add_user(new_user) user_id = self.db.user_id_check(user_name) new_account = Account(user_id) self.db.add_account(new_account) else: self.view.username_exists() self.create_account() return user_name, password def current_balance(self, user_name): balance = self.db.get_account_balance(self.db.user_id_check(user_name)) self.view.get_balance(balance[0]) return balance def run(self): signin = self.view.signin() if signin == "1": user_name, password = self.login() validate = self.db.signin(user_name, password) while validate == None: self.view.wrong_username_or_password() user_name, password = self.login() validate = self.db.signin(user_name, password) if validate[1] == 1: self.view.welcome_admin() dict_leaders = {} portfolios = self.db.get_all_portfolios() for portfolio in portfolios: key = portfolio[1] if key in dict_leaders: value, paid, profit = self.db.one_portfolio_value(portfolio) l = dict_leaders.get(key) for idx, num in enumerate(l): if idx == 0: value = num + value elif idx == 1: paid = num + paid else: profit = num + profit dict_leaders[key] = [value, paid, profit] else: value, paid, profit = self.db.one_portfolio_value(portfolio) dict_leaders[key] = [value, paid, profit] self.view.leaderboard(dict_leaders) elif signin == "2": user_name, password = self.create_account() else: self.view.invalid_choice() user_id = self.get_id(user_name) while True: action = self.view.user_menu() if action == "1": self.current_balance(user_name) portfolio = self.db.get_own_portfolio(user_id) self.view.list_all_portfolios(portfolio) value, paid, profit = self.db.current_portfolio_value(portfolio) self.view.print_current_portfolio_value(value, paid, profit) elif action == "2": search_type = self.view.search_type() if search_type == "1": company = self.view.search_by_company() info = self.view.company_info(self.api.company_search(company)) if self.api.company_search(company) == []: self.view.company_not_found() else: self.view.search_instructions() elif search_type == "2": symbol = self.view.search_by_symbol() self.api.get_company_data(symbol) self.view.company_data(self.api.get_company_data(symbol)) self.view.current_value(symbol, self.api.get_quote(symbol)) elif action == "3": balance = self.current_balance(user_name) symbol = self.view.search_by_symbol() price = self.api.get_quote(symbol) if price == None: self.view.company_not_found() else: self.view.current_value(symbol, price) quantity = self.view.get_quantity() total_price = price * float(quantity) self.view.get_total_price(total_price) if total_price > balance[0]: self.view.insufficient_funds() else: confirm = self.view.confirm_purchase() if confirm.lower() == "c": self.db.add_to_portfolio(user_id, symbol, price, quantity) self.db.update_account(total_price*-1, user_id) self.current_balance(user_name) elif confirm == "q": continue elif action == "4": symbol = self.view.stocks_to_be_sold() price = self.api.get_quote(symbol) stocks_with_symbol = self.db.get_from_portfolio(symbol, user_id) self.view.list_all_portfolios(stocks_with_symbol) number_of_stocks = self.db.get_number_of_stocks_available(symbol, user_id) if number_of_stocks[0][0] == None: self.view.company_not_found() continue self.view.show_number_of_stocks(symbol, number_of_stocks[0]) sell = int(self.view.how_many_for_sale()) while sell > number_of_stocks[0][0] or sell < 1: self.view.invalid_number() sell = int(self.view.how_many_for_sale()) price_paid = self.db.subtract_stocks(sell, stocks_with_symbol) profit = sell * price profit_loss = profit - price_paid self.view.show_profit_loss(profit_loss) self.db.update_account(profit, user_id) self.db.remove_zero_stocks() elif action == "5": break else: self.view.press_number()
def retrieve_company_data(company_name): markit_object = Markit() company_data = pd.DataFrame.from_dict( markit_object.company_search(company_name)) return company_data
def __init__(self): self.n=Markit()