def getMyStockListwithPrice(): stock_list = {} my_stocks_info = r.build_holdings() #print(my_stocks_info) for key in my_stocks_info.keys(): stock_list[key] = float(my_stocks_info[key]['price']) return stock_list
def write_return_percentages(): with open(PATH_TO_RETURN_TARGETS, 'w') as f: data = rs.build_holdings() final = {} for stock, stock_data in data.items(): final[stock] = float(stock_data['percent_change']) f.write(json.dumps(final))
def printRobinhoodSymbols(): print( '\n----------------------------------- Robinhood Symbols -----------------------------------' ) login = robinhood.login('*****@*****.**', '54bR&Srkm7EU') my_stocks = robinhood.build_holdings() for ticker in my_stocks.keys(): print(ticker)
def get_holding_earnings(): print("From the holdings:") my_stocks = r.build_holdings() stocks_earning = [(symbol, r.stocks.get_earnings(symbol)) for symbol in my_stocks.keys()] stocks_earning.sort(key=lambda x: datetime.datetime.strptime( get_next_eps_date(x[1]), date_time_pattern)) print_stocks_earning(stocks_earning)
def rh_get_holdings(): """ Get the current login account's current holdings with dividends included. return: pd.Dataframe -- The current account's holdings. """ holdings = rh.build_holdings(with_dividends=True) return holdings
def get(self, request, format=None): login = r.login(os.getenv("ROBINHOOD_USER"), os.getenv("ROBINHOOD_PASS")) stonks = r.build_holdings() for key, value in stonks.items(): print(key) print(value) return Response(stonks)
def RetrievePortfolio(self): try: # Pull down an update of the current holdings self.portfolio = rs.build_holdings() # Update the user profile self.profile = rs.build_user_profile() except Exception as e: raise StockAPIException(e)
def get_holdings(): holdings = rs.build_holdings() holdingValues = {} logging.info(f' Stock Quantity') for key, value in holdings.items(): logging.info(f' {key:5}: {value["quantity"].rjust(13)}') holdingValues.setdefault(key, []).append(value['quantity']) return holdingValues
def load_holdings( t: datetime, online: bool, log: bool ) -> Dict[str, HoldingInfo]: """ Hits the Robinhood API to pull down user's holdings data. """ holding_info_base_dir: str = os.path.join("data", "holdings") holding_info_output_dir: str = os.path.join( holding_info_base_dir, t.strftime("%Y"), t.strftime("%m"), t.strftime("%d"), t.strftime("%H"), t.strftime("%M"), t.strftime("%S"), ) resp: List[Dict[str, Any]] = [] if online: resp = list(r.build_holdings().values()) if log: if not os.path.exists(holding_info_output_dir): os.makedirs(holding_info_output_dir) holding_info_output_file = os.path.join( holding_info_output_dir, "{}.json".format(t.strftime("%Y_%m_%d_%H_%M_%S")), ) with open(holding_info_output_file, "w") as f: f.write(json.dumps(resp, indent=4)) else: latest = datetime.strptime( latest_ds(holding_info_base_dir), "%Y/%m/%d/%H/%M/%S" ) holding_info_latest_file: str = os.path.join( holding_info_base_dir, latest.strftime("%Y"), latest.strftime("%m"), latest.strftime("%d"), latest.strftime("%H"), latest.strftime("%M"), latest.strftime("%S"), "{}.json".format(latest.strftime("%Y_%m_%d_%H_%M_%S")), ) resp = json.load(open(holding_info_latest_file, "r")) holdings: Dict[str, HoldingInfo] = {} for s in resp: s_id: str = s["id"] holdings[s_id] = HoldingInfo( s_id, s["name"], float(s["price"]), int(float(s["quantity"])), float(s["average_buy_price"]), float(s["equity"]), float(s["percentage"]), float(s["percent_change"]), float(s["equity_change"]), ) return holdings
def build_portfolio(cls): """ :return: """ shares = [] for ticker in robin_stocks.build_holdings().keys(): shares.append(stock_wrapper.Shares(ticker)) return shares
def get_holdings(): """Returns dictionary of the currently held stocks""" my_stocks = robin.build_holdings() # stores in dataframe df = pd.DataFrame(my_stocks) df = df.transpose() df['ticker'] = df.index df = df.reset_index(drop=True) return df
def main(): #2FA step: totp = pyotp.TOTP("My2factorAppHere").now() l = robin_stocks.authentication.login(username=config.username, password=config.password, store_session=True, mfa_code=totp) #l = log-in info r = robin_stocks.build_holdings( ) #builds dictionary regard stocks+positions the owner has #initializing variable new_access = True print_holdings = False #Output holdings to console. Increases pie chart load time. #visual header for holdings data if (print_holdings == True): dash = '=' * 73 print(dash) print("Stonk: Curr_price:\t Shares Owned:") print(dash) for key, val in r.items(): #key = ticker symbol, val = ticker data if (new_access == True): total = np.array([]) ticker = np.array([]) portfolio_sum = 0 new_access = False if (print_holdings == True): print("{:<5s}\t {:>6.2f}\t\t{:>3.4f}".format( key, float(val['price']), float(val['quantity']))) #calculate stock price value and add it to total portfolio value tot = float(val['price']) * float(val['quantity']) portfolio_sum = portfolio_sum + tot ticker = np.append(ticker, str(key)) total = np.append(total, tot) #create pie chart with stock data + tickers as labels layout = go.Layout( title='<span style="font-size:30px">Current Robinhood Portfolio:</span>' + '<br>' + 'Value: ~$' + '{:.2f}'.format(portfolio_sum)) fig = go.Figure(data=[ go.Pie(labels=ticker, values=total, textinfo='label', hoverinfo='label+percent') ], layout=layout) fig.update_layout(autosize=True) # fig.show() robin_stocks.authentication.logout()
def sell_short(self, stock): if self.my_stocks: try: for i in self.my_stocks: if i == stock: bal = float(i['quantity']) r.order_sell_market(stock, bal) print('sold ' + str(bal) + ' : ' + stock) self.my_stocks = r.build_holdings() except Exception as e: print(e)
def getShareData(self, symbol): holdings = self.masterFormat(robin_stocks.build_holdings(), "holding") stock = None for holding in holdings: if robin_stocks.get_name_by_symbol(symbol) == holding.get("name"): stock = holding stock["sell_val"] = str( round( float(stock.get("average_buy_price")) - (float(stock.get("average_buy_price")) * 0.07), 2)) return stock
def __init__(self): login = r.login(LOGIN_EMAIL, LOGIN_PASSWORD, expiresIn=10, by_sms=False) self.holdings = r.build_holdings() self.securities = [] self.prices = {} self.equity = {} self.profile = r.profiles.load_portfolio_profile() self.acct = r.profiles.load_account_profile()
async def positions(ctx): # portfolio """ Displays a table of current stock holdings :param ctx: :return: Return string with multiple lines of stocks """ my_stocks = robin_stocks.build_holdings() positions = '' for key, value in my_stocks.items(): positions += ''.join(('{key}, Price: {price}, Quantity: {quantity}\n'.format(key=key, price=str(round(float(value['price']), 2)), quantity=str(round(float(value['quantity'])))))) await ctx.send(positions)
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 view_holdings(): print("\nPresenting all current user holdings") print('---------------------------- --------') try: for ticker, data in bot_trader.build_holdings().items(): print(ticker, ': ') for key, value in data.items(): print('\t', key, ': ', value) except Exception as holdings_err: exception_log(holdings_err) print('------------------------------------\n')
def buy_long(self, stock): buying_power = float(r.profiles.load_account_profile() ['margin_balances']['day_trade_buying_power']) if not self.my_stocks: try: qty = floor(buying_power / float(r.stocks.get_latest_price(stock)[0])) r.order_buy_market(stock, qty) print('bought ' + str(qty) + ' : ' + stock) self.my_stocks = r.build_holdings() except Exception as e: print(e)
def listStocksInAccount(self): if not self.isLogin: logger.logInfo( 'Please log in before listing stocks in the account.') return myStocks = robin.build_holdings() if len(myStocks.items()) == 0: logger.logInfo('This account hold 0 stocks.') else: logger.logInfo('Listing stocks:') for key, value in myStocks.items(): logger.logInfo(str(key) + ':' + str(value))
def __init__(self): with open("robinhood", "r", newline="\n") as file: username, password = file.read().strip().split("\n") r.login(username=username, password=password) cash = float(r.load_account_profile("cash")) super().__init__(cash) holdings = r.build_holdings() for symbol in holdings.keys(): holding = holdings[symbol] self.tickets[symbol] = float(holding["quantity"])
def get_equity_data(): """Displays a pie chart of your portfolio holdings """ holdings_data = r.build_holdings() equity_data = {} for key, value in holdings_data.items(): equity_data[key] = {} equity_data[key][name] = value.get('name') equity_data[key][percentage] = value.get("percentage") equity_data[key][type] fig1, ax1 = plt.subplots() ax1.pie(equities, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') plt.show()
def get(self, request, format=None): login = r.login(os.getenv("ROBINHOOD_USER"), os.getenv("ROBINHOOD_PASS")) stonks = r.build_holdings() for key, value in stonks.items(): if Stock.objects.filter(uuid=value['id']).count() != 1: stock = Stock.objects.create(user=request.user.profile, quantity=ceil( float(value['quantity'])), ticker=key, buy_price=value['price'], uuid=value['id']) queryset = request.user.profile.stocks.all() serializer = StockSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
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
def __init__(self, asset_classes, cash_allocation, test=False): self.test = test click.echo('Getting portfolio...') self.holdings = [] holdings = rs.build_holdings() for name, setting in asset_classes.items(): self.holdings.append(AssetClass(name, setting, holdings)) self.total_equity = sum([ac.equity for ac in self.holdings]) self.total_alloc = sum([ac.target_allocation for ac in self.holdings]) self.normalize_allocations() self.cash = max( 0, float(rs.load_account_profile()['buying_power']) - 0.01 - cash_allocation) if test: self.cash += 200
def run(self): stdscr = curses.initscr() curses.noecho() curses.cbreak() try: holdings = robin_stocks.build_holdings() i = 0 while duration == -1 or i < duration * 20: y = 0 for stock in self.stocks: to_print = stock + "\t" + str( self.__get_stock_price(stock)) if self.show_quantity: to_print += "\t" + str( int(float(holdings[stock]['quantity']))) if self.show_equity: to_print += "\t" + str( float(holdings[stock]['equity'])) stdscr.addstr(y, 0, to_print) y += 1 if 0 < len(self.stocks_to_monitor): y += 1 for stock in self.stocks_to_monitor: if stock not in self.stocks: stdscr.addstr( y, 0, stock + "\t" + str(self.__get_stock_price(stock))) stdscr.refresh() time.sleep(0.05) i += 1 finally: curses.echo() curses.nocbreak() curses.endwin()
def create(self, request, *args, **kwargs): import copy data = copy.deepcopy(request.data) data.update({'user': request.user}) serializer = StockCreateSerializer(data=request.data) serializer.is_valid(raise_exception=True) login = r.login(os.getenv("ROBINHOOD_USER"), os.getenv("ROBINHOOD_PASS")) order = r.order_buy_market(symbol=serializer.data['ticker'], quantity=serializer.data['quantity']) stonks = r.build_holdings() for key, value in stonks.items(): if Stock.objects.filter(uuid=value['id']).count() != 1: stock = Stock.objects.create(user=request.user.profile, quantity=ceil( float(value['quantity'])), ticker=key, buy_price=value['price'], uuid=value['id']) return Response(serializer.data, status=status.HTTP_200_OK)
def get_new_stocks(): play_money = float(r.load_account_profile()['margin_balances'].get('day_trade_buying_power')) current_holdings = r.build_holdings().keys() for g in g_sorted[:1]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price*.995), 2), timeInForce='gfd') play_money = play_money - (shares_to_buy * g.last_trade_price) print('placed for today ', g.Name) for g in tomorrow[:1]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money / g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .985), 2), timeInForce='gfd') play_money = play_money - (shares_to_buy * g.last_trade_price) print('placed for tomorrow ', g.Name) for g in g_sorted[1:2]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .995), 2), timeInForce='gfd') print('Runner up today ', g.Name) for g in tomorrow[1:2]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .98), 2), timeInForce='gfd') print('Runner up tomorrow ', g.Name)
def get_robin_data(self, username, password): """ :param username: enter robinhood username :param password: enter robinhood password :return: a dictionary of your Robinhood stocks """ try: # Creates a connection with Robinhood login = robin_stocks.login(username, password) except Exception as e: print(e, "Username or Password is incorrect.") # Pulls in user portfolio data from Robinhood my_stocks = robin_stocks.build_holdings() robinhood_dict = dict() # Extracts Ticker symbols as well as quantity of each ticker and average buy price of that ticker # Store that data in a list for key, value in my_stocks.items(): robinhood_dict[key] = [value['quantity'], value['average_buy_price']] # Add stock to portfolio text file self.__add_stock_from_robinhood(robinhood_dict) return robinhood_dict
def get_my_positions(self): my_stocks = robin_stocks.build_holdings() my_stocks_out = '''''' for symbol, info in my_stocks.items(): previous_close = float( robin_stocks.stocks.get_quotes(symbol)[0] ['adjusted_previous_close']) current_price = float( robin_stocks.stocks.get_latest_price(symbol)[0]) today_change = current_price - previous_close my_stocks_out = my_stocks_out + '''{} Equity: Today {}, Overall {} ({}%) \n'''.format( get_stock_data(symbol), round(float(info['quantity']) * today_change, 2), round(float(info['equity_change']), 2), info['percent_change']) print(my_stocks_out) return my_stocks_out