def _process_forex(self, row : Dict[str, str]) ->Trade: date_time = datetime.strptime(row["Date/Time"], '%Y-%m-%d, %H:%M:%S') # 2019-07-01, 14:48:19 price: float = float(row["T. Price"].replace(",", "")) quantity: float = float(row["Quantity"].replace(",", "")) proceeds: float = float(row["Proceeds"].replace(",", "")) commission: float = float(row["Comm in AUD"].replace(",", "")) symbol: str = str(row["Symbol"]) currency: str = str(row["Currency"]) asset_category: str = str(row["Asset Category"].upper()) # Fix strange Interactive Brokers convention of setting AUD as quanity and USD amount as proceeds. # Possibly a result of indirect quoting. Swapping quantity/proceeds and AUD.USD to USD.AUD. if symbol == "AUD.USD": return Trade("USD.AUD", asset_category, date_time, 1 / price, # NB: converted to USD.AUD. # This is a bit of a hack as there should be a conversion class to # handle this. Keep as market convention quote, convert all floats to # Amounts which contain Currency and have a translater divide or # multiply as required to convert. "AUD", # Hack: Report seems to use USD? proceeds, Amount(commission, "AUD"), 'BROKER_REPORT') else: raise NotImplementedError( "Only AUD.USD currency trades implemented as I am unsure how IB treats other currencies.")
def _process_trade(self, row : Dict[str, str]) -> Trade: date_time = datetime.strptime(row["Date/Time"], '%Y-%m-%d, %H:%M:%S') # 2019-07-01, 14:48:19 #price: float = float(row["T. Price"].replace(",", "")) # Cannot use as contracts might have multipliers. quantity: float = float(row["Quantity"].replace(",", "")) proceeds: float = float(row["Notional Value"].replace(",", "")) commission: float = float(row["Comm/Fee"].replace(",", "")) symbol: str = str(row["Symbol"]) currency: str = str(row["Currency"]) asset_category: str = str(row["Asset Category"]).upper() effective_price = abs(proceeds / quantity) return Trade(symbol, asset_category, date_time, effective_price, currency, quantity, Amount(commission, currency), 'BROKER_REPORT')
def open_new_trade(user, currency): """ Returns a new trade """ user = get_user(msg=user) affiliate = get_affiliate(user.chat) if affiliate != None: affiliate = affiliate.id trade = Trade( id=generate_id(), seller=user.id, currency=currency, payment_status=False, created_at=str(datetime.now()), updated_at=str(datetime.now()), is_open=True, affiliate_id=affiliate, ) session.add(trade) session.commit()
import pandas as pd import json import datetime from model import Pair, Trade fp = open("input_csv/ed_trade_data.json") jsondata = json.load(fp) pairlist = jsondata.keys() total_data = [] for i in pairlist: pair = Pair(i) pair_data = jsondata[str(pair)] trades = [] for j in pair_data: trade = Trade(i, j) trades.append(trade) total_data.append(trades) print pd.DataFrame(total_data)
import pandas as pd import json import datetime from model import Pair, Trade fp = open("input_csv/ed_trade_data.json") jsondata = json.load(fp) pairlist = jsondata.keys() y = { u'amount': u'510', u'amountBase': u'0.01377', u'buyer': u'0x13e2c5f84bce6ff7b9068313b21729dc8fd55d5a', u'seller': u'0x96e1e7ba823796772bbda5c2abe81c8556b5e937', u'tokenAddr': u'0x814964b1bceaf24e26296d031eadf134a2ca4105', u'txHash': u'0x122b9d6932b50d748d7848aae071cf41f7df8baa1400472dbcc4182bf3287478' } b = Trade('ETH_NEWB', y) print b
def calculate_proceeds( self, trades: List[TranslatedTrade]) -> List[TranslatedTrade]: matched_trades: List[MatchedInventory[ TranslatedTrade]] = self.inventory_accountant.match_trades(trades) proceed_trades: List[TranslatedTrade] = list(trades) for matched_trade in matched_trades: if matched_trade.buy_trade.currency != 'AUD': # Estimate gain/loss in foreign currency. price_difference = matched_trade.sell_trade.price - matched_trade.buy_trade.price proceeds = matched_trade.quantity * price_difference # Create effective trade to account for FX flow from foreign asset sale. # ATO translates all foreign assets to AUD for tax purposes on trade. If there is a foreign # currency gain/loss then the fx cost base is the ATO fx rate at sale. proxy_trade = Trade(matched_trade.sell_trade.currency + '.AUD', 'FOREX', matched_trade.sell_trade.date, matched_trade.sell_trade.exchange_rate, 'AUD', proceeds, Amount(0, 'AUD'), 'SALE_PROCEEDS') # Set the FX rate/price to the ATO-based FX rate used on selling the underlying asset. taxable_proxy_trade = TranslatedTrade( proxy_trade, matched_trade.sell_trade.exchange_rate, 1, 0, 'AUD') proceed_trades.append(taxable_proxy_trade) #And again for the buy commission if matched_trade.buy_trade.commission.currency != 'AUD': proportion_matched = matched_trade.quantity / abs( matched_trade.buy_trade.quantity) proxy_trade = Trade( matched_trade.buy_trade.currency + '.AUD', 'FOREX', matched_trade.buy_trade.date, matched_trade.buy_trade.exchange_rate, 'AUD', proportion_matched * matched_trade.buy_trade.commission.value, Amount(0, 'AUD'), 'COMMISSION') taxable_proxy_trade = TranslatedTrade( proxy_trade, proportion_matched * matched_trade.buy_trade.exchange_rate, 1, 0, 'AUD') proceed_trades.append(taxable_proxy_trade) # And one mroe for the sell commission if matched_trade.sell_trade.commission.currency != 'AUD': proportion_matched = matched_trade.quantity / abs( matched_trade.sell_trade.quantity) proxy_trade = Trade( matched_trade.sell_trade.currency + '.AUD', 'FOREX', matched_trade.sell_trade.date, matched_trade.sell_trade.exchange_rate, 'AUD', proportion_matched * matched_trade.sell_trade.commission.value, Amount(0, 'AUD'), 'COMMISSION') taxable_proxy_trade = TranslatedTrade( proxy_trade, proportion_matched * matched_trade.sell_trade.exchange_rate, 1, 0, 'AUD') proceed_trades.append(taxable_proxy_trade) # Static method to help with sorting def get_date(t: Trade) -> datetime: return t.date sorted_trades = sorted(proceed_trades, key=get_date) return sorted_trades
return q def read_trade_price(): """ Get Trade Price from input """ trade_price = float(0) while(True): q = raw_input("Enter trade price:") try: trade_price = float(q) break except: print("Invalid trade price. Try again.") return trade_price if __name__ == '__main__': print('Please select stocks from '+(",".join(symbol_list))) trades = [] while(True): symbol = read_stock_symbol() market_price = read_trade_price() q = read_trade_quantity() current_stock = service.get_stock_by_symbol(symbol) trades.append(Trade(trade_count.next(), time.time(), current_stock.id, q, market_price, "BUY")) print("PE Ratio for "+symbol+":"+str(round(service.get_pe_ratio(market_price, symbol),3 ))) print("Dividend yield for "+symbol+":"+str(round(service.get_dividend_yeild(market_price, symbol), 3))) print("VSMP for "+symbol+":"+str(round(service.get_volume_weighted_stock_price(trades, current_stock.id),3))) print("Geometric Mean for "+symbol+":"+str(round(service.get_geometric_mean(trades, current_stock.id), 3))) print("\n")