def get_watchlist_symbols(): """ Returns: the symbol for each stock in your watchlist as a list of strings """ my_list_names = [] symbols = [] for name in r.get_all_watchlists(info='name'): my_list_names.append(name) for name in my_list_names: list = r.get_watchlist_by_name(name) for item in list: instrument_data = r.get_instrument_by_url(item.get('instrument')) symbol = instrument_data['symbol'] symbols.append(symbol) return symbols
def rh_pull_symbol_from_instrument_url(url): obj = robinhood_traded_stocks.objects.filter(instrument_url=url) if not obj: obj = robinhood_traded_stocks() symbol = r.get_instrument_by_url(url)['symbol'] name = r.get_name_by_symbol(symbol) obj.symbol = symbol obj.name = name obj.instrument_url = url obj.save() else: obj = obj[0] symbol = obj.symbol name = obj.name return symbol, name
def import_portfolio_robinhood(access_token, username=None, password=None, name="Robinhood", free_stock=False): """ Accesses Robinhood account and downloads transactions Parameters ========== username : Robinhood username password : Robinhood account password name : desired portfolio name free_stock : include a free stock not captured by transaction history (see below) Returns ======= df : dataframe with transactions p : portfolio (Portfolio class object) """ if not access_token: if username is None: username = getpass("Username: "******"Password: "******"Parsing orders ...") # pre-pull all tickers before creating order history df Tickerset = [] for order in orders: if len(order["executions"]): Tickerset.append(order["instrument"]) Tickerset = list(set(Tickerset)) # make a lookup dict for ticker symbols Tickersymbols = {} for element in Tickerset: Tickersymbols[element] = r.get_instrument_by_url(element)["symbol"] for order in orders: if len(order["executions"]): Date.append(pd.to_datetime(order["last_transaction_at"])) Transaction.append(order["side"]) Ticker.append(Tickersymbols[order["instrument"]]) Currency.append("USD") Price.append(order["average_price"]) Quantity.append(order["quantity"]) # add deposits transfers = r.get_bank_transfers() print("Parsing bank transfers ...") for transfer in transfers: if transfer["cancel"] is None: Date.append(pd.to_datetime(transfer["created_at"])) Transaction.append(transfer["direction"]) Ticker.append(None) Currency.append("USD") Price.append(1.0) Quantity.append(transfer["amount"]) # add dividends dividends = r.get_dividends() print("Parsing dividends ...") for dividend in dividends: if dividend["state"] == "paid": Date.append(pd.to_datetime(dividend["paid_at"])) Transaction.append("dividend") Ticker.append(Tickersymbols[dividend["instrument"]]) Currency.append("USD") Price.append(1.0) Quantity.append(dividend["amount"]) if free_stock == True: # include free stock (Robinhood promotion, not included in transaction history) print("Adding promotional stock ...") Date.append(pd.to_datetime("2/1/18")) Transaction.append("buy") Ticker.append("CHK") Currency.append("USD") Price.append(0.0) Quantity.append(1.0) # build dataframe d = { "Date": Date, "Transaction": Transaction, "Ticker": Ticker, "Currency": Currency, "Price": pd.to_numeric(Price), "Quantity": pd.to_numeric(Quantity), } df = pd.DataFrame(data=d) # strip time of day information df.Date = df.Date.map(lambda x: x.strftime("%m-%d-%Y")) df.Date = pd.to_datetime(df.Date) # create a new portfolio object p = Portfolio(name=name) # parse p = parse_portfolio(df, p) return p
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: try: if s in quantities: print("\n" + s + " stock sellable: " + str(quantities[s])) # print("\n"+s+" last trade price: "+str(d[s])) Ltp = d[s] # print(s+" Ask: "+str(ask(s))) Ask = ask(s) # print(s+" Bid: "+str(bid(s))) Bid = bid(s)
def import_portfolio_robinhood(username=None, password=None, name="Robinhood", free_stock=False): """ Accesses Robinhood account and downloads transactions Parameters ========== username : Robinhood username password : Robinhood account password name : desired portfolio name free_stock : include a free stock not captured by transaction history (see below) Returns ======= df : dataframe with transactions p : portfolio (Portfolio class object) """ import robin_stocks as r from getpass import getpass if username is None: username = getpass("Username: "******"Password: "******"Parsing orders ...") for order in orders: if len(order['executions']): Date.append(pd.to_datetime(order['last_transaction_at'])) Transaction.append(order['side']) Ticker.append( r.get_instrument_by_url(order['instrument'])['symbol']) Currency.append('USD') Price.append(order['average_price']) Quantity.append(order['quantity']) # add deposits transfers = r.get_bank_transfers() print("Parsing bank transfers ...") for transfer in transfers: if transfer['cancel'] is None: Date.append(pd.to_datetime(transfer['created_at'])) Transaction.append('deposit') Ticker.append(None) Currency.append('USD') Price.append(1.0) Quantity.append(transfer['amount']) # add dividends dividends = r.get_dividends() print("Parsing dividends ...") for dividend in dividends: if dividend['state'] == 'paid': Date.append(pd.to_datetime(dividend['paid_at'])) Transaction.append('dividend') Ticker.append( r.get_instrument_by_url(dividend['instrument'])['symbol']) Currency.append('USD') Price.append( float(dividend['amount']) / float(dividend['position'])) Quantity.append(dividend['position']) if free_stock == True: # include free stock (Robinhood promotion, not included in transaction history) print("Adding promotional stock ...") Date.append(pd.to_datetime('2/1/18')) Transaction.append('buy') Ticker.append('CHK') Currency.append('USD') Price.append(0.0) Quantity.append(1.0) # build dataframe d = { 'Date': Date, 'Transaction': Transaction, 'Ticker': Ticker, 'Currency': Currency, 'Price': pd.to_numeric(Price), 'Quantity': pd.to_numeric(Quantity) } df = pd.DataFrame(data=d) # strip time of day information df.Date = df.Date.map(lambda x: x.strftime('%m-%d-%Y')) df.Date = pd.to_datetime(df.Date) # create a new portfolio object p = Portfolio(name=name) # parse p = parse_portfolio(df, p) return p
def load_securities( security_ids: List[str], t: datetime, online: bool, log: bool ) -> Dict[str, SecurityInfo]: """ Hits the Robinhood API to pull down security information like the latest price and the full security name. """ security_info_base_dir: str = os.path.join("data", "securities") security_info_output_dir: str = os.path.join( security_info_base_dir, t.strftime("%Y"), t.strftime("%m"), t.strftime("%d"), t.strftime("%H"), t.strftime("%M"), t.strftime("%S"), ) resp: Dict[str, Any] = {} if online: for sec_id in security_ids: sec_url = os.path.join( "https://api.robinhood.com", "instruments", sec_id ) sec_meta = r.get_instrument_by_url(sec_url) sec_name = sec_meta["name"] sec_sym = sec_meta["symbol"] sec_price = r.get_latest_price(sec_sym) resp[sec_id] = { "name": sec_name, "symbol": sec_sym, "price": sec_price, } if log: if not os.path.exists(security_info_output_dir): os.makedirs(security_info_output_dir) security_info_output_file = os.path.join( security_info_output_dir, "{}.json".format(t.strftime("%Y_%m_%d_%H_%M_%S")), ) with open(security_info_output_file, "w") as f: f.write(json.dumps(resp, indent=4)) else: latest = datetime.strptime( latest_ds(security_info_base_dir), "%Y/%m/%d/%H/%M/%S" ) security_info_latest_file: str = os.path.join( security_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(security_info_latest_file, "r")) security_info: Dict[str, SecurityInfo] = {} for (sec_id, info) in resp.items(): security_info[sec_id] = SecurityInfo( info["name"], info["symbol"], float(info["price"][0]) ) return security_info