def showBlotter(self, user): from get_currency_info import get_current if self.blotter_rows > 0: if user.currency != 'USDT': cur = get_current(user.currency, 'check') mult = 1 / cur #Going from dollars to the currency, intead of directly to from currency #to prevents the problem of certain currencies pairs not trading. #It also makes the program neater for such a minor difference, since this is #only for display purposes. else: mult = 1 #prepare for display df = self.blotter.copy() df.loc[:, ['price', 'net', 'cash_balance']] *= mult df["price"] = df["price"].map('${:,.2f}'.format) df["net"] = df["net"].map('${:,.2f}'.format) df["cash_balance"] = df["cash_balance"].map('${:,.2f}'.format) dates = df.index df['Transaction Date'] = dates df = df[[ 'Transaction Date', "currency", "price", "shares", "tran_type", "net", "cash_balance" ]] to_string = lambda x: '{:,.8f}'.format(x).rstrip('0').rstrip('.') df['shares'] = df['shares'].map(to_string) labels = [ "Transaction Date", "Currency", "Price", "Shares Traded", "Transaction Type", "Net Cash Flow", "Cash Balance" ] df.columns = labels self.blotter_view = df
def forest_predict(model, ticker, user): from get_currency_info import get_current X, y = forest_prep(ticker) pred = model.predict(X.iloc[-1:, :].values.reshape(1, -1)) forecast = get_current(ticker, 'check') * (1 + pred[0]) * user.get_mult() return '${:,.2f}'.format(forecast)
def get_mult(self): from get_currency_info import get_current if self.currency != 'USDT': cur = get_current(self.currency, 'check') else: cur = 1 return 1 / cur
def check_margin(self): from get_currency_info import get_current margin = 0 for currency in self.pl.index: if self.pl.loc[currency, "position"] < 0: margin += self.pl.loc[currency, "position"] * get_current( currency, "buy") * -1 return margin
def garch_predict(ticker, user): from arch import arch_model from get_currency_info import get_current returns = prepare_returns( ticker)['log_ret'] * 10 #to prevent underflow during fit am = arch_model(returns, p=1, o=0, q=2, dist='StudentsT') res = am.fit(update_freq=5, disp='off') change = res.forecast(horizon=1).mean.iloc[-1, 0] / 10 forecast = get_current(ticker, 'check') * (1 + change) * user.get_mult() return '${:,.2f}'.format(forecast)
def preview_trade(): from get_currency_info import get_current, find_actives ticker = request.form['ticker'] trade_type = request.form['type'] shares = request.form['shares'] if ticker.upper() in find_actives(): cur = get_current(ticker, trade_type) if test_inputs(cur, shares): cur_format = "${:,.2f}".format(cur) tot = cur * float(shares) tot_format = "${:,.2f}".format(tot) return (jsonify(current = cur_format, total = tot_format)) else: return jsonify(current = 'Problem with order size or ticker', total = '') else: return jsonify(current = 'Ticker not found', total = '')
def executeTrade(): from get_currency_info import get_current, find_actives ticker = request.form['ticker'].upper() trade_type = request.form['type'] shares = request.form['shares'] if ticker in find_actives(): #test front end input price = get_current(ticker, trade_type) if test_inputs(price, shares): #test front end input account.evalTransaction(trade_type, float(shares), price, ticker, my_db, my_pl, my_blotter) if account.message == 'Success': #test business logic return jsonify(message = 'Order Success! {}@${:,.2f}'.format(ticker, price)) else: return(jsonify(message = account.message)) else: return jsonify(message = 'Problem with order size or ticker') else: return(jsonify(message = 'Ticker not found'))
def showPL(self, user): import numpy as np from get_currency_info import get_current #for showing PL in different currencies if user.currency != 'USDT': cur = get_current(user.currency, 'check') mult = 1 / cur else: mult = 1 final_df = self.pl.copy()[self.pl.index != 'cash'] #create a dataframe from positions for easy calculated columns markets = [] for position in final_df.index.values: market = get_current(position, 'check') markets.append(market) final_df["market"] = markets cash = self.pl.loc['cash', 'market'] * mult #additional columns calculated from "base" data final_df.loc[:, "total_value"] = final_df.position * final_df.market final_df.loc[:, 'share_weight'] = abs(final_df.position) / np.sum( abs(final_df.position)) final_df.loc[:, 'value_weight'] = abs(final_df['total_value']) / np.sum( abs(final_df['total_value'])) final_df.loc[:, "upl"] = final_df.position * final_df.market - final_df.position * final_df.wap final_df.loc[:, 'tpl'] = final_df.upl + final_df.rpl final_df.fillna(0) final_df.replace(np.nan, 0, inplace=True) currencies = final_df.index final_df['currency'] = currencies final_df = final_df[[ 'currency', "position", "market", "total_value", 'value_weight', 'share_weight', "wap", "upl", 'rpl', "tpl" ]] final_df.loc[:, ['tpl', 'market', 'rpl', 'total_value', 'wap', 'upl' ]] *= mult #total row val = cash + np.sum(final_df["total_value"]) totals = [ 'Total', '', '', val, '', '', '', np.sum(final_df["upl"]), np.sum(final_df["rpl"]), np.sum(final_df["tpl"]) ] #format total row for item in range(len(totals)): if type(totals[item]) is not str: totals[item] = "${:,.2f}".format(totals[item]) totals = tuple(totals) cash_row = ("Cash", '', '', "${:,.2f}".format(cash), '', '', '', '', '', '') space_row = tuple(['' for i in range(len(final_df.columns))]) #format currency rows for item in ["market", "total_value", "wap", "upl", "rpl", 'tpl']: final_df[item] = final_df[item].map('${:,.2f}'.format) for item in ['value_weight', 'share_weight']: final_df[item] = (final_df[item] * 100).map('{:,.1f}%'.format) to_string = lambda x: '{:,.8f}'.format(x).rstrip('0').rstrip('.') final_df['position'] = final_df['position'].map(to_string) rows = len(final_df) final_df.loc[rows] = cash_row final_df.loc[rows + 1] = space_row final_df.loc[rows + 2] = totals cols = [ 'Currency', "Position", "Market Price", "Total Value", 'Value Weight', 'Share Weight', "WAP", "UPL", "RPL", 'Total PL' ] final_df.columns = cols self.pl_view = final_df
def showPL(self, user, db): import numpy as np from get_currency_info import get_current from price_predictions import garch_predict, forest_predict from datetime import datetime #for showing PL in different currencies mult = user.get_mult() final_df = self.pl.copy()[self.pl.index != 'cash'] #isolate the actual currencies from cash markets = [] garch_predictions = [] forest_predictions = [] for position in final_df.index.values: market = get_current(position, 'check') markets.append(market) if position in ('BTC', 'ETH'): garch_predictions.append(garch_predict(position, user)) if position == 'ETH': forest_predictions.append( forest_predict(self.eth_forest, position, user)) else: forest_predictions.append( forest_predict(self.btc_forest, position, user)) else: garch_predictions.append(0) forest_predictions.append(0) final_df["market"] = markets final_df.loc[:, 'price_pred_garch'] = garch_predictions final_df.loc[:, 'price_pred_forest'] = forest_predictions cash = self.pl.loc['cash', 'market'] * mult #additional columns calculated from "base" data final_df['total_value'] = final_df.position * final_df.market final_df.loc[:, 'share_weight'] = abs(final_df.position) / np.sum( abs(final_df.position)) final_df.loc[:, 'value_weight'] = abs(final_df['total_value']) / np.sum( abs(final_df['total_value'])) final_df[ 'upl'] = final_df.position * final_df.market - final_df.position * final_df.wap final_df['tpl'] = final_df.upl + final_df.rpl final_df.fillna(0) final_df.replace(np.nan, 0, inplace=True) currencies = final_df.index final_df['currency'] = currencies final_df = final_df[[ 'currency', "position", "market", "total_value", 'value_weight', 'share_weight', "wap", "upl", 'rpl', "tpl", 'price_pred_garch', 'price_pred_forest' ]] final_df.loc[:, ['tpl', 'market', 'rpl', 'total_value', 'wap', 'upl' ]] *= mult #total row val = cash + np.sum(final_df["total_value"]) self.tpl = np.sum(final_df["tpl"]) totals = [ 'Total', '', '', val, '', '', '', np.sum(final_df["upl"]), np.sum(final_df["rpl"]), self.tpl, '', '' ] #format total row for item in range(len(totals)): if type(totals[item]) is not str: totals[item] = "${:,.2f}".format(totals[item]) totals = tuple(totals) cash_row = ("Cash", '', '', "${:,.2f}".format(cash), '', '', '', '', '', '', '', '') space_row = tuple(['' for i in range(len(final_df.columns))]) #format currency rows for item in ["market", "total_value", "wap", "upl", "rpl", 'tpl']: final_df[item] = final_df[item].map('${:,.2f}'.format) for item in ['value_weight', 'share_weight']: final_df[item] = (final_df[item] * 100).map('{:.1f}%'.format) to_string = lambda x: '{:,.8f}'.format(x).rstrip('0').rstrip('.') final_df['position'] = final_df['position'].map(to_string) rows = len(final_df) final_df.loc[rows] = cash_row final_df.loc[rows + 1] = space_row final_df.loc[rows + 2] = totals cols = [ 'Currency', "Position", "Market Price", "Total Value", 'Value Weight', 'Share Weight', "WAP", "UPL", "RPL", 'Total PL', 'Price Prediction (GARCH)', 'Price Prediction (Random Forest)' ] final_df.columns = cols self.pl_view = final_df
def eval_pl(self, tran_type, shares, price, ticker, total, db, new, prev_shares, date): #only certain columns that form the "base" data are calculated here. #Columns like upl are only calculated when the user views the pl because #those rely on market value. This approach should be more efficient #in terms of performance and coding from get_currency_info import get_current market = get_current(ticker, 'check') if tran_type in ('buy', 'cover'): self.pl.loc['cash', 'market'] -= total if new == 0: new_shares = prev_shares + shares if tran_type == "buy": if self.pl.loc[ticker, "position"] == 0: self.pl.loc[ticker, 'wap'] = price self.pl_hist.loc[ date, ['ticker', 'wap', 'position', 'rpl']] = ( ticker, price, new_shares, 0) self.calc_tpl(ticker, date, new_shares, price, market, 0) else: wap = self.calc_wap(prev_shares, shares, new_shares, price, 1, ticker) self.pl.loc[ticker, 'wap'] = wap self.pl_hist.loc[ date, ['ticker', 'wap', 'position', 'rpl']] = ( ticker, wap, new_shares, 0) self.calc_tpl(ticker, date, new_shares, wap, market, 0) else: #Cover wap = self.pl.loc[ticker, "wap"] gain = wap * shares - total rpl = self.pl.loc[ticker, "rpl"] + gain self.pl.loc[ticker, "rpl"] = rpl self.pl_hist.loc[date, ['ticker', 'rpl', 'position', 'wap']] = ( ticker, rpl, new_shares, wap) self.calc_tpl(ticker, date, new_shares, wap, market, gain) #both self.pl.loc[ticker, "position"] = new_shares if new_shares == 0: #for aesthetics in the P&L self.pl.loc[ticker, "wap"] = 0 db.pl_update(self.pl, ticker) db.pl_update(self.pl, 'cash') db.pl_hist_insert(self.pl_hist, date) else: #new currencies self.pl.loc[ticker, [ 'position', 'market', 'wap', 'rpl', 'upl', 'tpl', 'allocation_by_dollars', 'allocation_by_shares' ]] = (shares, 0, price, 0, 0, 0, 0, 0) self.pl_hist.loc[date, ['ticker', 'wap', 'rpl', 'position']] = ( ticker, price, 0, shares) self.calc_tpl(ticker, date, shares, price, market, 0) db.pl_insert(self.pl, ticker) db.pl_hist_insert(self.pl_hist, date) db.pl_update(self.pl, 'cash') else: #sell/short self.pl.loc['cash', 'market'] += total if new == 0: new_shares = self.pl.loc[ticker, 'position'] - shares if tran_type == "sell": wap = self.pl.loc[ticker, 'wap'] gain = total - wap * shares self.pl.loc[ticker, 'rpl'] = self.pl.loc[ticker, "rpl"] + gain self.pl_hist.loc[date, ['rpl', 'ticker', 'position', 'wap']] = ( gain, ticker, new_shares, wap) self.calc_tpl(ticker, date, new_shares, wap, market, gain) else: #short if self.pl.loc[ticker, 'position'] == 0: self.pl.loc[ticker, "wap"] = price self.pl_hist.loc[ date, ['ticker', 'wap', 'position', 'rpl']] = ( ticker, price, new_shares, 0) self.calc_tpl(ticker, date, new_shares, price, market, 0) else: wap = self.calc_wap(prev_shares, shares, new_shares, price, -1, ticker) self.pl.loc[ticker, "wap"] = wap self.pl_hist.loc[ date, ['ticker', 'wap', 'position', 'rpl']] = ( ticker, wap, new_shares, 0) self.calc_tpl(ticker, date, new_shares, wap, market, 0) #both self.pl.loc[ticker, "position"] = new_shares if new_shares == 0: self.pl.loc[ticker, "wap"] = 0 db.pl_update(self.pl, ticker) db.pl_update(self.pl, 'cash') db.pl_hist_insert(self.pl_hist, date) else: #new currencies self.pl.loc[ticker, [ 'position', 'market', 'wap', 'rpl', 'upl', 'tpl', 'allocation_by_dollars', 'allocation_by_shares' ]] = (-shares, 0, price, 0, 0, -shares * price, 0, 0) self.pl_hist.loc[date, ['ticker', 'wap', 'rpl', 'position']] = ( ticker, price, 0, -shares) self.calc_tpl(ticker, date, -shares, price, market, 0) db.pl_insert(self.pl, ticker) db.pl_hist_insert(self.pl_hist, date) db.pl_update(self.pl, 'cash')
from datetime import datetime, timedelta from pymongo import MongoClient import pandas as pd connection = MongoClient('ds149279.mlab.com', 49279) db = connection['data602final'] db.authenticate('me', 'mypass') trades = [] for option in available['instrumentName'].values: trades.append(last_trades(option)) df = pd.DataFrame(trades) df['indexPrice'] = get_current('btc', 'check') df.rename(columns={ 'instrumentName': 'instrument', 'askPrice': 'price', 'created': 'timeStamp', 'volume': 'quantity' }, inplace=True) sds = pd.DataFrame([item for item in db.sds.find({})]) get_date = lambda x: datetime.strptime(x, '%d%b%y') get_cols = lambda x: pd.Series([item for item in x.split('-')]) cols = df['instrument'].apply(get_cols) cols.columns = ['uderlying', 'expiration_date', 'strike', 'option_type']