Example #1
0
 def test_latest_price(self):
     price = r.get_latest_price(self.single_stock)
     assert (len(price) == 1)
     more_prices = r.get_latest_price(self.list_stocks)
     assert (len(more_prices) == len(self.list_stocks))
     fake_prices = r.get_latest_price(self.fake_stocks)
     assert (len(fake_prices) == 1)
     assert (fake_prices[0] == None)
Example #2
0
def buy_holdings(potential_buys, profile_data, holdings_data):
    """ Places orders to buy holdings of stocks. This method will try to order
        an appropriate amount of shares such that your holdings of the stock will
        roughly match the average for the rest of your portfoilio. If the share
        price is too high considering the rest of your holdings and the amount of
        buying power in your account, it will not order any shares.

    Args:
        potential_buys(list): List of strings, the strings are the symbols of stocks we want to buy
        symbol(str): Symbol of the stock we want to sell
        holdings_data(dict): dict obtained from r.build_holdings() or get_modified_holdings() method
    """
    cash = float(profile_data.get('cash'))
    portfolio_value = float(profile_data.get('equity')) - cash
    ideal_position_size = (safe_division(portfolio_value, len(holdings_data))+cash/len(potential_buys))/(2 * len(potential_buys))
    prices = r.get_latest_price(potential_buys)
    for i in range(0, len(potential_buys)):
        stock_price = float(prices[i])
        if(ideal_position_size < stock_price < ideal_position_size*1.5):
            num_shares = int(ideal_position_size*1.5/stock_price)
        elif (stock_price < ideal_position_size):
            num_shares = int(ideal_position_size/stock_price)
        else:
            print("####### Tried buying shares of " + potential_buys[i] + ", but not enough buying power to do so#######")
            break
        print("####### Buying " + str(num_shares) + " shares of " + potential_buys[i] + " #######")
        if not debug:
            r.order_buy_market(potential_buys[i], num_shares)
Example #3
0
def buyInvestments(args):
    print(f'buyInvestments')
    login()

    investments=readJSON(config['investmentsPath'])
    symbols = []
    for item in investments:
        symbols.append(item['symbol'])

    current_prices = rh.get_latest_price(symbols)
    spread=math.floor(args.amount/len(investments)) #equally divided for now

    plan=[]
    for security in investments:
        symbol=security['symbol']
        price=float(current_prices.pop(0))
        quantity=price/spread
        plan.append({'symbol':symbol, 'quantity':quantity})

    for security in plan:
        print(f"buy symbol: {security['symbol']:>4s} quantity: {security['quantity']:13.8f}")
        
    if (args.dryrun):
        print('Dryrun. No action taken')
        return
        
    if (readTrueFalse('execute trade (y/n)?')):
        for security in plan:
            print(f"executed {security['symbol']:>4s} quantity: {security['quantity']:13.8f}")
    else:
        print('No action taken')
Example #4
0
def buy(syms: typing.List[str], profile, holdings, dry_run: bool):
    """Buy holdings of stock, matching average holdings in the rest of your portfolio (magic?)."""
    cash = float(profile.get('cash'))
    portfolio_value = float(profile.get('equity')) - cash
    ideal_position_size = (safe_division(portfolio_value, len(holdings)) +
                           cash / len(syms)) / (2 * len(syms))
    prices = robinhood.get_latest_price(syms)

    for i in range(0, len(syms)):
        stock_price = float(prices[i])
        if (ideal_position_size < stock_price < ideal_position_size * 1.5):
            num_shares = int(ideal_position_size * 1.5 / stock_price)
        elif (stock_price < ideal_position_size):
            num_shares = int(ideal_position_size / stock_price)
        else:
            logging.warning("####### Tried buying shares of " + syms[i] +
                            ", but not enough buying power to do so#######")
            break

        logging.info("####### Buying " + str(num_shares) + " shares of " +
                     syms[i] + " #######")
        if not dry_run:
            robinhood.order_buy_market(syms[i], num_shares)
Example #5
0
def round_up_price(ticker, multiplier):
    price = float(r.get_latest_price(ticker)[0])
    num = price + (multiplier - 1)
    return num - (num % multiplier)
Example #6
0
def QUOTE(ticker):
    r = rh.get_latest_price(ticker)
    print('Latest ',ticker,r)
    return r[0]
Example #7
0
 def returnCompanyInfo(self, symbol):
     return rs.get_instruments_by_symbols(symbol), rs.get_latest_price(
         symbol)
Example #8
0
    def returnDayWeekSummary(self, offset, interval, latest=False):
        """
        Return day or week summary by the end of day or week
        """
        sanity_check = self.__returnDayWeekStockHistory(
            "SPY", offset, interval)
        if sanity_check == None:
            return None

        current_floating_earnings = 0
        total_history_trans_earnings = 0
        total_fees = 0
        total_cash_flow = 0

        summary = {}

        merged_orders = self.__returnMergedOrders()

        for symbol, transactions in merged_orders.items():
            # print(symbol, len(transactions))

            current_quantity = 0
            current_trans_amount = 0

            history_trans_amount = 0

            for transaction in transactions:
                if transaction["state"] == "filled" and transaction[
                        "last_transaction_at"] <= sanity_check["ends_at"]:
                    side = transaction["side"]
                    cumulative_quantity = float(
                        transaction["cumulative_quantity"])
                    average_price = float(transaction["average_price"])
                    total_fees = total_fees + float(transaction["fees"])
                    if side == "buy":
                        current_quantity += cumulative_quantity
                        current_trans_amount -= cumulative_quantity * average_price
                    else:
                        current_quantity -= cumulative_quantity
                        current_trans_amount += cumulative_quantity * average_price
                    if isClose(current_quantity, 0):
                        history_trans_amount += current_trans_amount
                        current_quantity = 0
                        current_trans_amount = 0
            total_history_trans_earnings += history_trans_amount
            total_cash_flow += current_trans_amount
            # print("Total Trans Earnings:", FormatNumber(history_trans_amount, "{:.2f}", "$"))
            if not isClose(current_quantity, 0):
                price = 0
                if latest:
                    price = float(
                        rs.get_latest_price(symbol,
                                            includeExtendedHours=True)[0])
                else:
                    stock_history = self.__returnDayWeekStockHistory(
                        symbol, offset, interval)
                    if stock_history["interpolated"]:
                        # print("False date, using 10minute data instead")
                        stock_history = self.__returnTodayStockHistory(symbol)
                    # print(stock_history)
                    price = float(stock_history["close_price"])
                # print("Price:", price)
                # print("Quantity:", FormatNumber(current_quantity, "{:.2f}"))
                floating_earning = price * current_quantity + current_trans_amount
                current_floating_earnings += floating_earning
                # print("Floating Earning:", FormatNumber(floating_earning, "{:.2f}", "$"))
            # print("-------------------------------")

        if latest:
            summary["datetime"] = self.__end_datetime
            summary["principles"] = self.returnPrinciplesBalance()
            summary["dividends"] = self.returnTotalDividends()
        else:
            summary["datetime"] = sanity_check["ends_at"]
            summary["principles"] = self.returnPrinciplesBalance(
                sanity_check["ends_at"])
            summary["dividends"] = self.returnTotalDividends(
                sanity_check["ends_at"])

        summary["current_floating_earnings"] = current_floating_earnings
        summary["total_history_trans_earnings"] = total_history_trans_earnings
        summary["total_cash_flow"] = total_cash_flow
        summary["principles"] = self.returnPrinciplesBalance(
            sanity_check["ends_at"])
        summary["dividends"] = self.returnTotalDividends(
            sanity_check["ends_at"])
        summary["total_cash_flow"] = total_cash_flow
        summary["total_fees"] = total_fees

        return summary