def robinbot(buy, sell): totp = pyotp.TOTP(config.robin_totp).now() print("Current OTP: ", totp) login = robin_stocks.login(config.robin_user, config.robin_pwd, mfa_code=totp) holdings = robin_stocks.get_open_stock_positions() print(buy) print(sell) for stock in sell: stock = stock.strip() if stock in holdings: quantity = holdings[stock]["quantity"] robin_stocks.order_sell_fractional_by_quantity(stock, quantity, 'gfd') acc = robin_stocks.load_account_profile() print(acc) bp = acc["portfolio_cash"] print(bp) bp = float(bp) if bp > 0: bpps = bp/len(buy) print(bpps) for stock in buy: order = robin_stocks.order_buy_fractional_by_price(stock, bpps, 'gfd') print(order) else: print("not enough buying power") robin_stocks.logout()
def get_current_positions(self): data = r.get_open_stock_positions() holdings = list() for item in data: item['symbol'] = r.get_symbol_by_url(item['instrument']) # Returns current_price object for a give symbol helperFunction = Helpers(item['symbol']) currentData = helperFunction.currentPrices() current_equity = float(item['quantity']) * float( currentData['ask_price']) price_paid = float(item['quantity']) * float( item['average_buy_price']) singleHolding = { "symbol": item['symbol'], "quantity": item['quantity'], "current_price": currentData['ask_price'], "average_buy_price": item['average_buy_price'], "price_paid": round(price_paid, 2), "current_equity": round(current_equity, 2), "profit": round(float(current_equity) - float(price_paid), 2) } holdings.append(singleHolding) return holdings
def get_modified_holdings(): """Retrieves same dictionary as with robin.build_holdings but includes information when the stock was purchased - useful for the read_trade_history() method in tradingstats.py """ holdings = robin.build_holdings() holdings_data = robin.get_open_stock_positions() for symbol, dict in holdings.items(): bought_at = get_position_creation_date(symbol, holdings_data) bought_at = str(pd.to_datetime(bought_at)) holdings[symbol].update({'bought_at': bought_at}) return holdings
def get_portfolio_symbols(): """ Returns: the symbol for each stock in your portfolio as a list of strings """ symbols = [] holdings_data = r.get_open_stock_positions() for item in holdings_data: if not item: continue instrument_data = r.get_instrument_by_url(item.get('instrument')) symbol = instrument_data['symbol'] symbols.append(symbol) return symbols
def get_modified_holdings(): """ Retrieves the same dictionary as r.build_holdings, but includes data about when the stock was purchased, which is useful for the read_trade_history() method in tradingstats.py Returns: the same dict from r.build_holdings, but with an extra key-value pair for each position you have, which is 'bought_at': (the time the stock was purchased) """ holdings = r.build_holdings() holdings_data = r.get_open_stock_positions() for symbol, dict in holdings.items(): bought_at = get_position_creation_date(symbol, holdings_data) bought_at = str(pd.to_datetime(bought_at)) holdings[symbol].update({'bought_at': bought_at}) return holdings
import robin_stocks as r import os login = r.login('*****@*****.**', 'password') ## Query AAPL positions_data = r.get_open_stock_positions() prof = r.profiles.load_account_profile(info=None) # print(prof) inputSymbols = ["AAPL"] aapl = r.stocks.get_fundamentals(inputSymbols, info=None) print(aapl) ## Shit shit out file1 = open('symbols.txt', 'r') lines = file1.readlines() strip_lines = [] for line in lines: strip_lines.append(line.strip()) print("S******g out information for") print(strip_lines) market_caps = {} for symbol in strip_lines: info = r.stocks.get_fundamentals(symbol, info=None)
def rh_pull_portfolio_data(user_id, passwd): r.login(username=user_id, password=passwd) if DbAccess.is_update_needed(): obj = portfolio_summary.objects.all() if not obj: obj = portfolio_summary() obj.timestamp = timezone.now() else: obj = obj[0] obj.portfolio_cash = float(profiles.load_account_profile()['portfolio_cash']) obj.save() # remove current entries stocks_held.objects.all().delete() # get current owned securites and save to db positions_data = r.get_open_stock_positions() for item in positions_data: quantity = float(item['quantity']) if not quantity: continue # check if instrument is present in robinhood_traded_stocks table obj = stocks_held() obj.symbol, obj.name = RhWrapper.rh_pull_symbol_from_instrument_url(item['instrument']) obj.quantity = quantity obj.average_price = float(item['average_buy_price']) obj.latest_price = float(r.get_latest_price(obj.symbol)[0]) obj.open_price = float(r.get_fundamentals(obj.symbol)[0]['open']) try: obj.prev_close_price = float(StockUtils.getStockInfo(obj.symbol)['previousClose']) except Exception as e: logging.error(str(e) + ' encountered when fetching yahoo data for ' + obj.symbol) obj.prev_close_price = obj.open_price obj.save() # remove current entries options_held.objects.all().delete() # get current owned securites and save to db options_position_data = r.get_open_option_positions() for item in options_position_data: quantity = float(item['quantity']) if not quantity: continue obj = options_held() obj.option_id = item['option_id'] contract_into = r.get_option_instrument_data_by_id(obj.option_id) obj.strike_price = float(contract_into['strike_price']) obj.expiration_date = contract_into['expiration_date'] obj.option_type = contract_into['type'] obj.symbol = item['chain_symbol'] obj.trade_value_multiplier = float(item['trade_value_multiplier']) obj.average_price = float(item['average_price']) / obj.trade_value_multiplier obj.quantity = float(item['quantity']) # adjust value for sold calls if obj.average_price < 0: obj.average_price = (-1) * obj.average_price obj.quantity = (-1) * obj.quantity market_data = r.get_option_market_data_by_id(obj.option_id) obj.previous_close_price = float(market_data['previous_close_price']) obj.current_price = float(market_data['adjusted_mark_price']) # print('symbol: %5s strike_price: %7.2f option_type: %4s expiration_date: %12s trade_value_multiplier: %d average_price: %7.2f quantity: %d previous_close_price: %7.2f current_price: %7.2f' % (obj.symbol, obj.strike_price, obj.option_type, obj.expiration_date, obj.trade_value_multiplier, obj.average_price, obj.quantity, obj.previous_close_price, obj.current_price)) obj.save()
def positions(): result = rh.get_open_stock_positions() ui.success(result)
def test_open_stock(self): stock = r.get_open_stock_positions(info=None) self.assertNotEqual(len(stock), 0)
ans = input( "Press <Enter> when you have created rh_stock_data.json in the RHAST folder" ) print("\nrh_stock_data.json in the RAT folder looks like...\n") with open(stock_file) as json_data: d = json.load(json_data) print(json.dumps(d, indent=1)) input( "\nYour stocks and the last trade prices of each on your account?\n\n<enter> if everything looks correct.\n" ) numSymbols = len(d) # print(numSymbols) positions = r.get_open_stock_positions() numPositions = len(positions) quantities = {} for i in range(0, numPositions): # print(positions[i]) # print(json.dumps(positions[i],indent=1)) quantities[r.get_instrument_by_url( positions[i]["instrument"])["symbol"]] = float( positions[i]["quantity"]) index = 0 check = {} #s is symbol, d is the whole rh_stock_data json dictionary for s in d:
def getPortfolio(self): self.portfolio = r.get_open_stock_positions() self.simplifyList(self.portfolio)
def LOAD_OPEN_STOCKS(): func = r.get_open_stock_positions() return func
def getStockPositions(): positions_data = rs.get_open_stock_positions() for item in positions_data: item['symbol'] = rs.get_symbol_by_url(item['instrument']) print(item['symbols'])