Esempio n. 1
0
def generate_top_news():
    start_time = time.time()
    r.login(username, password)

    # Get list of stocks in watchlist and positions.
    stocks_dict = {}
    watchlist = r.get_watchlist_by_name()
    positions = r.get_current_positions()
    stocks = watchlist + positions

    # Get stock info (e.g. ticker, name) for each stock.
    with ThreadPoolExecutor(max_workers=20) as executor:
        stock_info_futures = [
            executor.submit(r.request_get, stock['instrument'])
            for stock in stocks
        ]
    for stock_info_future in as_completed(stock_info_futures):
        stock_info = stock_info_future.result()
        ticker = stock_info['symbol']
        stock = Stock(stock_info['simple_name'], ticker)
        stocks_dict[ticker] = stock
    print("--- %s seconds --- (Got all tickers)" % (time.time() - start_time))

    # Get top news for all stocks (prioritized by num_clicks).
    # TODO: Consider prioritizing by date also.
    news_heap = []
    news_dict = {}
    with ThreadPoolExecutor(max_workers=20) as executor:
        news_futures_to_ticker = {
            executor.submit(r.get_news, stock.ticker): stock.ticker
            for stock in stocks_dict.values()
        }
    for news_future in as_completed(news_futures_to_ticker):
        ticker = news_futures_to_ticker[news_future]
        news = news_future.result()
        if not news:
            continue
        recent_news = news[0]
        # Rank news by views. Need to retain metadata for ticker, source, title, and views.
        num_clicks = recent_news['num_clicks']
        source = recent_news['api_source']
        title = recent_news['title']
        # (-views, ticker, source, title)
        heapq.heappush(news_heap, (-num_clicks, ticker, source, title))
    print("--- %s seconds --- (Got all news)" % (time.time() - start_time))

    # TTS for top news.
    news_aggregate = []
    for news in news_heap[:5]:
        ticker, source, title = news[1], news[2], news[3]
        stock_news_string = "Top news for stock " + stocks_dict[
            ticker].name + ", "
        news_source_string = "from " + source + ": "
        news_aggregate.append(stock_news_string + news_source_string + title +
                              "\n")
    print("--- %s seconds --- (End)" % (time.time() - start_time))
    return ''.join(news_aggregate)
def get_portfolio_symbols():
    """
    Returns: the symbol for each stock in your portfolio as a list of strings
    """
    symbols = []
    holdings_data = r.get_current_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_current_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 sell_old_stocks():
    divies = [[x.get('instrument'), x.get('record_date')] for x in r.get_dividends()]
    positions_data = r.get_current_positions()
    for position in positions_data:
        for d in divies:
            if position.get('instrument') in d[0]:
                about = r.request_get(position['instrument'])
                div_diff = (datetime.strptime(d[1], '%Y-%m-%d') - today).days
                if div_diff <= 0:
                    stock_dict = r.stocks.get_stock_quote_by_symbol(about.get('symbol'))
                    last_trade_price = float(stock_dict.get('last_trade_price'))
                    if last_trade_price / float(position['average_buy_price']) > 1.005:
                        if float(position.get('shares_held_for_sells')) == 0:
                            if easygui.ccbox(msg=about.get('symbol') + '\n' + d[1] + '\nQuantity: ' + str(position['quantity']) + '\nPurchase $' + str(float(position['average_buy_price'])) + '\nCurrent price $' + str(last_trade_price) + '\nProfit per $' + str(float(last_trade_price) - float(position['average_buy_price'])) + '\nTotal win $' + str((float(last_trade_price) - float(position['average_buy_price']))*float(position['quantity'])) + '\nROI ' + str(100 - (float(last_trade_price) / float(position['average_buy_price']))*-100) + '%'  ):
                                r.order_sell_limit(about.get('symbol'), position['quantity'], round(last_trade_price*1.0035, 2))
                                print('selling ', about.get('symbol'))
                else:
                    stock_dict = r.stocks.get_stock_quote_by_symbol(about.get('symbol'))
                    last_trade_price = float(stock_dict.get('last_trade_price'))
                    if last_trade_price / float(position['average_buy_price']) > 1.015:
                        if float(position.get('shares_held_for_sells')) == 0:
                            if easygui.ccbox(msg='NO DIVVIE SALE\n' +about.get('symbol') + '\n' + d[1] + '\nQuantity: ' + str(position['quantity']) + '\nPurchase $' + str(float(position['average_buy_price'])) + '\nCurrent price $' + str(last_trade_price) + '\nProfit per $' + str(float(last_trade_price) - float(position['average_buy_price'])) + '\nTotal win $' + str((float(last_trade_price) - float(position['average_buy_price'])) * float(position['quantity'])) + '\nROI ' + str(100 - (float(last_trade_price) / float(position['average_buy_price'])) * -100) + '%'):
                                r.order_sell_limit(about.get('symbol'), position['quantity'], round(last_trade_price * 1.0035, 2))
                                print('selling ', about.get('symbol'))
Esempio n. 5
0
#----------------------------
# helpers
def time_stamp():   
    utc_now = pytz.utc.localize(datetime.utcnow())
    est_now = utc_now.astimezone(pytz.timezone("America/New_York")) 
    dt_string = est_now.strftime("%b-%d, %Y: %H:%M:%S")
    print(dt_string)
    return dt_string

def buy(quantity):
    price = 147.87
    twilio.send_msg("Bought " + str(quantity) + "shares @ $" + str(price))
#----------------------------
# MODELS:
TA_List = np.full(23500,-1)
portfolio = robin.get_current_positions()
ms_stocks = portfolio['MSFT']['quantity']
# Linear_reg_list = []
#----------------------------
# CONFIG 
funds = 0
permitted = False
stock_symbol = "MSFT"

#-------

# log in
robin.login(config.rh_usr_name, config.rh_password)

# get current holdings
    # {
Esempio n. 6
0
import wget
import json
import stocks as s
'''
Robinhood portfolio script

'''

#!!! Fill out username and password
username = ''
password = ''
#!!!

login = r.login(username, password)

mypos = r.get_current_positions()

for counter in mypos:
    mystring = counter['instrument']
    myr = requests.get(mystring)
    try:
        jdata = (json.loads(myr.content))
    except ValueError as e:
        #print(" ")
        continue
    except:
        continue

    try:
        print("Name:" + str(jdata['simple_name']))
    except ValueError as f:
Esempio n. 7
0
API documentation
http://www.robin-stocks.com/en/latest/functions.html#logging-in-and-out
"""

import robin_stocks as r
from cred_util import load_cred

real_buy_cell = False

#%%
########## info require login #############
cred = load_cred('../../credential/ini.json')
login = r.login(cred['robinhood']['username'], cred['robinhood']['password'])

## get all you current position
positions_data = r.get_current_positions()

## simple function to get all holdings
my_stocks = r.build_holdings()

# get some user profile data
profile_info = r.profiles.load_account_profile()
print(profile_info['crypto_buying_power'])

## load portfolio info
portfolio = r.profiles.load_portfolio_profile()
print(portfolio['last_core_portfolio_equity'])

##get stock information
stock = r.stocks.find_instrument_data('tesla')
stock_sym = stock[0]['symbol']
Esempio n. 8
0
def put_in_stop_loss_orders_all(
    access_token=None,
    username=None,
    password=None,
    portfolio=None,
    column="Close",
    alpha=0.5,
    sigmas=2,
):
    """
    Accesses Robinhood account and put in stop loss sell orders for all securities in a portfolio.
    Stop loss price is calculated as exponentially weighted average price and standard deviation.


    Parameters
    ==========
    username : Robinhood username
    password : Robinhood account password
    portfolio : portfolio name 
    free_stock : include a free stock not captured by transaction history (see below)

    Returns
    =======

    """

    import time

    if not access_token:
        if username is None:
            username = getpass("Username: "******"Password: "******"instrument"]) == r.get_name_by_symbol(ticker)
        ][0]

        # assert that portfolio positions are the same as returned from API
        if (portfolio.positions_df.Quantity[ticker] >
                0) & (portfolio.positions_df.Quantity[ticker] == float(
                    stock_data["quantity"])):
            portfolio.securities[ticker].latest_price = float(
                r.get_latest_price([ticker])[0])
            portfolio.securities[ticker].stop_loss_price = round(
                get_stop_loss_price(
                    security=portfolio.securities[ticker],
                    column=column,
                    alpha=alpha,
                    sigmas=sigmas,
                ),
                2,
            )
            quantity = float(stock_data["quantity"])

            # print out summary
            print(
                ticker,
                quantity,
                portfolio.securities[ticker].latest_price,
                portfolio.securities[ticker].last_price_ewm,
                portfolio.securities[ticker].stop_loss_price,
                portfolio.securities[ticker].stop_loss_price -
                portfolio.securities[ticker].last_price_ewm,
                100 * (portfolio.securities[ticker].stop_loss_price -
                       portfolio.securities[ticker].latest_price) /
                portfolio.securities[ticker].latest_price,
            )

            # put in the order
            r.order_sell_stop_loss(
                ticker, quantity, portfolio.securities[ticker].stop_loss_price)

            # Wait for a few seconds to not get thrown off Robinhood
            time.sleep(1)

        else:
            print(
                "Disagreement: ",
                ticker,
                portfolio.positions_df.Quantity[ticker],
                float(stock_data["quantity"]),
            )