示例#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)
示例#2
0
 def test_latest_price(self):
     price = r.get_latest_price(self.single_stock)
     self.assertEqual(len(price), 1)
     more_prices = r.get_latest_price(self.list_stocks)
     self.assertEqual(len(more_prices), len(self.list_stocks))
     fake_prices = r.get_latest_price(self.fake_stocks)
     self.assertEqual(len(fake_prices), 1)
     self.assertEqual(fake_prices[0], None)
示例#3
0
def tickerPrice(stock):
    """Returns last trade price for provided stock

    :param stock: {1-5} character stock-ticker
    :return: [float] current price
    """
    return float(r.get_latest_price(stock)[0])
示例#4
0
def last_price_generator(ticker_list=ticker_list):
    last_price = dict()
    for symbol in ticker_list:
        if '-' in symbol:
            symbol = symbol.replace("-", ".")
        last_price.update({symbol: float(r.get_latest_price(symbol)[0])})
    return last_price
示例#5
0
def scooper(stk, tup_sym):
    '''
    gather/format all of the information listed in primary docstring
    parameters:
        stk     -- dictionary for a stock (generated by get_top_movers)
        tup_sym -- list of tuples with formated information
    '''
    n_title = ''
    n_preview_text = ''

    current_price = rs.get_latest_price(stk['symbol'],
                                        includeExtendedHours=True)[0]
    news = rs.stocks.get_news(stk['symbol'])

    try:  # to get news
        n_title = news[0]['title']
        n_preview_text = news[0]['preview_text']
        n_preview_text = n_preview_text.replace(',', '')
        n_preview_text = n_preview_text.replace('\n', '')
        n_title = n_title.replace(',', '')
        n_title = n_title.replace('\n', '')
    except IndexError:  # that there is no news
        n_title = 'NA'
        n_preview_text = 'NA'

    sentiment = 0
    if n_preview_text != 'NA':
        openai.Completion.create(engine="davinci",
                                 prompt="{}".format(n_preview_text),
                                 max_tokens=5)

    tup_sym.append((stk['symbol'],
                    stk['price_movement']['market_hours_last_movement_pct'],
                    current_price, n_title, n_preview_text))
示例#6
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)
def quote(ticker):
    try:
        for element in ticker:
            element = element.upper()
            r = robin.get_latest_price(element)
            print(element.upper() + " $" + "{:.2f}".format(float(r[0])))
    except TypeError:
        print("Not a valid ticker symbol")
def printStocks(stocks):

    for stock in stocks:
        # Displays Stock name and latest price
        print(f'Stock name: {stock["name"]}')
        price = float(robin.get_latest_price(stock['symbol'])[0])
        price = "${:,.2f}".format(price)
        print(f'Price: {price}\n')
示例#9
0
def is_robin_stock(ticker):
    try:
        if r.get_latest_price(ticker) is not None:
            robin_tickers.append(ticker)
            print('ADDDED ' + ticker)
            return
        print('IDK ' + ticker)
    except:
        print('None for ' + ticker)
def find_options(s, filename, columns):
    market_utils.login()
    options = {}

    all_options = r.options.find_tradable_options(s, optionType='call')
    options['call'] = pd.DataFrame(
        market_utils.get_options(
            all_options, datetime.date(2021, 3, 31),
            r.get_latest_price(s, includeExtendedHours=False)[0]))
    try:
        options['call'][
            'ratio'] = options['call'].volume / options['call'].open_interest
        options['call'] = options['call'][
            (options['call'].ratio > 5) & (options['call'].ratio != np.inf) &
            (options['call'].volume >= 1000)].dropna()
    except AttributeError as message:
        print('{} for {}'.format(message, s))

    if len(options['call']) > 0:
        options['put'] = pd.Series([
            r.options.find_options_by_expiration_and_strike(
                s, exp_date, strike, optionType='put')[0]
            for (exp_date, strike) in zip(options['call'].expiration_date,
                                          options['call'].strike_price)
        ])
        options['call']['symbol'] = s
        options['call'].strike_price = options['call'].strike_price.astype(
            float)
        options['call'].last_trade_price = options[
            'call'].last_trade_price.astype(float)
        options['call'].adjusted_mark_price = options[
            'call'].adjusted_mark_price.astype(float)
        options['call'].previous_close_price = options[
            'call'].previous_close_price.astype(float)
        options['call'].implied_volatility = options[
            'call'].implied_volatility.astype(float)
        options['call'].chance_of_profit_long = options[
            'call'].chance_of_profit_long.astype(float)
        options['call'].chance_of_profit_short = options[
            'call'].chance_of_profit_short.astype(float)
        options['call']['put_volume'] = [x['volume'] for x in options['put']]
        options['call']['put_open'] = [
            x['open_interest'] for x in options['put']
        ]
        options['call']['put_ratio'] = options['call']['put_volume'] / options[
            'call']['put_open']

        options['call'].to_csv(filename,
                               mode='a',
                               header=False,
                               columns=columns,
                               index=False,
                               float_format='%.2f')
def add_price_log(symbol: str, expiration_date: str, buy_strike: float,
                  sell_strike: float, buy_price: float, sell_price: float,
                  current_price: float, stop_price: float,
                  profit_price: float):
    """Adds Credit Spread to config file"""
    file_location = 'C:/Users/Davet/OneDrive/Desktop/Robinhood/Price Records/Historical.csv'

    w = open(file_location, "a")
    w.write('{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}\n'.format(
        d.datetime.now(), symbol, expiration_date,
        float(rs.get_latest_price(symbol)[0]), buy_strike, sell_strike,
        buy_price, sell_price, current_price, stop_price, profit_price))
    w.close()
示例#12
0
def sell_stops(potential_buys):
    portfolio_symbols = get_portfolio_symbols()
    prices = r.get_latest_price(potential_buys)
    for i in range(0, len(potential_buys)):
        stock_price = float(prices[i])
        if potential_buys[i] in portfolio_symbols:
            r.order_sell_stop_limit(potential_buys[i],
                                    num_shares,
                                    stock_price,
                                    stock_price - 0.01,
                                    timeInForce='gtc')
            print("####### Sold " + str(num_shares) + " stop limits of " +
                  potential_buys[i] + " #######")
    print("----- Scan over -----\n")
def find_options(s):
    date_f = datetime.date.today().strftime('%Y%m%d')
    time_f = datetime.datetime.today().strftime('%H%M%S')
    outdir = '/Users/nickmartin/data/finance/{}/'.format(date_f)
    filename = '{}/unusual_{}_{}_{}_{}.csv'.format(outdir, 'call', 'test',
                                                   date_f, time_f)

    user = os.environ['robin_user']
    pwd = os.environ['robin_pass']
    r.login(user, pwd)

    all_options = r.options.find_tradable_options(s, optionType='call')
    options = option_utils.get_options(
        all_options, datetime.date(2020, 3, 31),
        r.get_latest_price(s, includeExtendedHours=False)[0])
    option_utils.write_uoa_file(filename, s, options)
示例#14
0
def perform_ta(arr):
    for i in arr: 
        if i != -1:
    np.build
    slope = LINEARREG_SLOPE()
    return slope


    while (seconds < time_interval):
        curr_price = floatx(robin.get_latest_price(test_symbol)[0])
        if (curr_price > entry_price):
            if (portfolio[test_symbol] != None): 
                buy(test_symbol)
        else:
            if (portfolio[test_symbol] != None): 
                sell(test_symbol)
        wait(1)
        output_to_log_file()
        seconds += 1
示例#15
0
past_stochastic_signal = np.full(len(share_data), 'None')
while True:
    if is_time_interval(second=5):
        print('Checking for potential trades...')
        for index_num, stock in enumerate(share_data):
            past_close_prices = stonks.get_stock_historicals(
                stock, interval='day', span='3month', info='close_price')
            past_low_prices = stonks.get_stock_historicals(stock,
                                                           interval='day',
                                                           span='3month',
                                                           info='low_price')
            past_high_prices = stonks.get_stock_historicals(stock,
                                                            interval='day',
                                                            span='3month',
                                                            info='high_price')
            current_price = float(stonks.get_latest_price(stock)[0])
            share_handler = buying_power / current_price * 0.1  # Amount of shares purchased in one interaction
            if share_handler < 1:
                share_handler = 1

            ema_twelve = stonk_calc.get_ema(
                all_share_data[share_index][index_num],
                current_price,
                period=12,
                past_close_prices=past_close_prices)
            ema_two_six = stonk_calc.get_ema(
                all_share_data,
                current_price,
                period=26,
                past_close_prices=past_close_prices)
            if pd.isnull(all_share_data.iloc[share_index[index_num]]['MACD']):
示例#16
0
    #         'equity': '13792.28', 
    #         'percent_change': '-10.58', 
    #         'equity_change': '-1631.705000', 
    #         'type': 'stock', 
    #         'name': 'Intelsat', 
    #         'id': 'b12f8af0-5c02-4ac3-b91b-c6557a78c19e', 
    #         'pe_ratio': None, 
    #         'percentage': '52.22'
    #     },
    # 'SPY':{},
    # 'SHOP':{}
    # }

# initialize
principal = 10000
curr_price = float(robin.get_latest_price(test_symbol)[0])
prev_price = float(robin.get_latest_price(test_symbol)[0])
time_interval = 300
f = open("raw-output1/raw-output-{month_str}-{day_str}-{year_str}.txt", "a")
i = 0
entry_price  = float(robin.get_latest_price(test_symbol)[0])
sleep(500)
curr_price = float(robin.get_latest_price(test_symbol)[0])

# filling
for (i = 0, i<15, i++): 
    price = robin.get_latest_price(stock_symbol)[0]
    TA_List[i] = float(price)
    f.write(price)
    sleep(1)
 
date_f = datetime.date.today().strftime('%Y%m%d')
time_f = datetime.datetime.today().strftime('%H%M%S')
outdir = '/Users/nickmartin/data/finance/{}/'.format(date_f)
if not os.path.exists(outdir):
    os.makedirs(outdir)
for option_type in option_types:
    filename = '{}/unusual_{}_{}_{}_{}.csv'.format(outdir, option_type, suffix,
                                                   date_f, time_f)
    with open(filename, 'w') as f:
        f.write(
            'Symbol,Exp Date,Strike,Last Traded,Money,Volume,Open,Ratio,Current Price,Prev Close Price,Imp Volatility,Long,Short\n'
        )

    count = 1
    for symbol in symbols:
        print('processing {} {} of {}: {}'.format(option_type, count,
                                                  len(symbols), symbol))
        count += 1
        try:
            all_options = r.options.find_tradable_options(
                symbol, optionType=option_type)
        except TypeError as message:
            print('for symbol in symbols {}: o man'.format(message))

        options, good_options, bad_options = option_utils.get_options(
            all_options, max_date,
            r.get_latest_price(symbol, includeExtendedHours=False)[0])
        option_utils.write_uoa_file(filename, symbol, options)

print('Run time: {} seconds'.format(time.time() - start_time))
def bid(symbol):  #test: works
    return float(r.get_latest_price(symbol, 'bid_price')[0])
示例#19
0
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") + "\n"
    print(dt_string)
    return dt_string


twilio.send_key_msg('start')

i = 0
while (i < 23000):
    try:
        #f.write(time_stamp())
        resp = robin.get_latest_price(watchlist_symbols)
        for j in range(len(files)):
            f = files[j]
            f.write(resp[j] + '\n')
            f.flush()
            #f.write("--------------------------------\n")
    except:
        for j in range(len(files)):
            f = files[j]
            f.write('-1' + '\n')
            f.flush()
        if not failed:
            twilio.notify_error_msg()
            failed = True
    i += 1
    sleep(1)
示例#20
0
def get_stock_price(ticker):
    return float(r.get_latest_price(ticker)[0])
示例#21
0
#def get_latest_price(inputSymbols, includeExtendedHours=True):
#def get_quotes(inputSymbols, info=None):
#def order_buy_limit(symbol, quantity, limitPrice, timeInForce='gtc', extendedHours=False):
#def order_sell_limit(symbol, quantity, limitPrice, timeInForce='gtc', extendedHours=False):

if __name__ == "__main__":

    # ticker = input("Which stock would you like to trade: ")
    ticker = 'BYFC'

    # login
    login = r.login(username, password)

    # print out a summary and ask what to do
    cur_price = round(float(r.get_latest_price(ticker)[0]), 2)
    print("Current Price: ", cur_price)

    # now what?
    trade = input("Would you like to buy or sell (b/s): ")
    shares = int(input("How many shares: "))
    price_target = float(input("What price: "))

    if trade == 'b':
        # this means we want to buy
        print(ticker, ": Limit buy order for", shares,
              "shares has been placed at $", price_target)
        r.order_buy_limit(ticker, shares, price_target)

    elif trade == 's':
        # this means we want to sell
示例#22
0
def data_updater():
    global data

    # track these for each 5 minute price interval
    price_open = 0
    price_close = 0
    price_high = 0
    price_low = 0
    last_minute = 0  # use this to make sure we just do one entry per 5 min
    rolling_price = 0
    last_price = 0

    # PID stuff
    _P_ = 5
    _I_ = 0.2
    _D_ = 20
    i_term = 0
    pid_term = 0

    # manage potfolio a little bit
    buy_open = False
    sell_open = False
    shares = 0  # assume we start with no shares

    while True:
        cur_time = datetime.datetime.now()
        cur_price = float(r.get_latest_price(ticker)[0])
        if rolling_price == 0:
            rolling_price = cur_price

        # calculate the 'rolling average'
        rolling_price = round(rolling_price * 0.5 + cur_price * 0.5, 3)
        spread = round((rolling_price - cur_price) / cur_price, 3)

        # i_term should roll
        i_term += spread * _I_
        pid_term = _P_ * spread + i_term + _D_ * (cur_price - last_price)

        # update for next time
        last_price = cur_price

        print(cur_price, rolling_price, pid_term)

        # update extremes for time interval
        if cur_price > price_high or price_high == 0:
            price_high = cur_price
        if cur_price < price_low or price_low == 0:
            price_low = cur_price
        if price_open == 0:
            price_open = cur_price

        # every 5 minutes, update another entry to our data struct
        if cur_time.minute % 5 == 0 and cur_time.minute != last_minute:

            # this will ensure we don't do more than one entry
            last_minute = cur_time.minute

            # convert to string to make my life easier
            cur_time = str(cur_time)

            # get the rigth index for the data dict addon
            day = cur_time.split(" ")[0]
            clock_time = cur_time.split(" ")[1].split(".")[0][:-2] + '00'
            TIME_INDEX = day + " " + clock_time

            # add an entry to the full data group so we can keep
            # making predictions
            addon = dict()
            addon['0. price'] = rolling_price
            addon['1. open'] = price_open
            addon['2. high'] = price_high
            addon['3. low'] = price_low
            addon['4. close'] = cur_price
            addon['5. volume'] = 0  # TODO
            addon['6. pid'] = pid_term

            data[TIME_INDEX] = addon

            # now, reset values we track
            price_open = price_close
            price_close = 0
            price_high = price_open
            price_low = price_open

        time.sleep(1)
def ask(symbol):  #test: works
    return float(r.get_latest_price(symbol, 'ask_price')[0])
示例#24
0
def round_up_price(ticker, multiplier):
    price = float(r.get_latest_price(ticker)[0])
    num = price + (multiplier - 1)
    return num - (num % multiplier)
tickers = ['UAL', 'AAL', 'JETS', 'GME', 'NOK', 'F', 'GE', 'OPK']
MIN_PREMIUM_PERCENTAGE = 1
# MAX_PREMIUM_PERCENTAGE = 2 # to use you must also uncomment code below
##############################################################

pwd = keyring.get_password("robinhood", "my_very_own_rh_username")
if pwd is None:
    print("First time? Securely type in your Robinhood Password please:")
    # Stores password in local system using keyring
    keyring.set_password("robinhood", "my_very_own_rh_username",
                         getpass.getpass())
    pwd = keyring.get_password("robinhood", "my_very_own_rh_username")

login = r.login(MY_RH_USERNAME, pwd)

latest_prices = r.get_latest_price(tickers)
prices = dict(zip(tickers, list(map(float, latest_prices))))

today = datetime.date.today()
friday = today + datetime.timedelta((4 - today.weekday()) % 7)
# If it's late in the week and you want to look at next week, uncomment the below line
# friday = friday + datetime.timedelta(7)

expiration = "{}-{}-{}".format(friday.year, friday.month, friday.day)

putData = r.find_options_by_expiration(tickers,
                                       expirationDate=expiration,
                                       optionType='put')

putsToLookAt = defaultdict(lambda: [])
for put in putData:
示例#26
0
    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()
示例#27
0
def stock_status(Ticker = "AMZN",raw_data=raw_data_all.copy(),\
                 last_price=last_price_all.copy(),epochs=100, batch_size=30,verbose = 0,plot=True):
    response = pdr.get_data_yahoo(Ticker, start=response_start_date, end=response_end_date,\
                                      progress=False)['Adj Close'].values[:-1]
    if Ticker in raw_data.keys():
        print("condition is ", response[-2] == raw_data[Ticker][-1])
        if response[-2] != raw_data[Ticker][-1]:
            response = response[:-1]
            print("condition is ", response[-2] == raw_data[Ticker][-1])

    if Ticker not in raw_data.keys():
        h = pdr.get_data_yahoo(Ticker,
                               start=start_date,
                               end=end_date,
                               progress=False)['Adj Close'].values
        raw_data.update({Ticker: h[:-1]})
        #we ignore the last sample
        if len(response) < len(raw_data[list(raw_data.keys())[0]]):
            for item in raw_data.items():
                raw_data.update({item[0]: item[1][-len(response):]})
    Input_data = pd.DataFrame.from_dict(raw_data)
    response_std = np.diff(response).std()
    #scale input
    scaler_x = preprocessing.StandardScaler().fit(Input_data)
    Input_data_scaled = scaler_x.transform(Input_data)
    #model
    model = Sequential()
    model.add(
        Dense(128,
              input_dim=len(Input_data.T),
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    #    model.add(Dense(16, activation='relu', kernel_initializer='lecun_normal',kernel_regularizer = l1_l2(0.001,0.001),activity_regularizer=l1_l2(0.001,0.001), bias_regularizer=l1_l2(0.001,0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(128,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(128,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(64,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(64,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(64,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(32,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(32,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(32,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(16,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(16,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dropout(0.4))
    model.add(
        Dense(16,
              activation='relu',
              kernel_initializer='lecun_normal',
              kernel_regularizer=l1_l2(0.001, 0.001),
              activity_regularizer=l1_l2(0.001, 0.001)))
    model.add(Dense(1, activation='linear'))
    model.compile(loss='mean_squared_error',
                  optimizer='Nadam',
                  metrics=['mae', 'mse'])
    #    es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10000)
    history = model.fit(Input_data_scaled, response,validation_split=0.4, epochs=epochs, \
              batch_size=batch_size,shuffle = True,verbose = verbose)#, callbacks=[es])

    hist = pd.DataFrame(history.history)
    print(f"\n{Ticker} done! with mae of {hist['val_mae'].values[-1]:.4}")
    #Prediction
    if Ticker.replace('-', '.') in last_price.keys():
        last_used_price = last_price[Ticker.replace('-', '.')]  #last price
    else:
        last_used_price = float(
            r.get_latest_price(Ticker.replace('-', '.'))[0])
        last_price[Ticker] = last_used_price
    x_pre = scaler_x.transform(
        np.array(list(last_price.values())).reshape(1, -1))
    predictions = model.predict(x_pre)
    diff = last_used_price - predictions
    status = str()
    if diff > 3 * response_std:
        status = "Strong sell"
    elif diff > 2 * response_std:
        status = "Sell"
    elif diff > -2 * response_std and diff < 2 * response_std:
        status = "Neutral"
    elif diff < -2 * response_std and diff > -3 * response_std:
        status = "Buy"
    else:
        status = "Strong buy"
    print(
        f"{status} with predicted price of {np.round(predictions[0][0],2):.4} and last price of {last_used_price}\n"
    )
    model.save(
        f'Models\{Ticker}_model.h5')  # creates a HDF5 file 'my_model.h5'
    del model  # deletes the existing model
    # summarize history for loss
    if plot:
        plt.close()
        plt.plot(np.sqrt(history.history['mse']))
        plt.plot(np.sqrt(history.history['val_mse']))
        RMSE = np.round(np.sqrt(hist["val_mse"].values[-1]), 2)
        plt.title(f'model RMSE for {Ticker}-ended:{RMSE}')
        plt.ylabel('RMSE')
        plt.xlabel('epoch')
        plt.legend(['train', 'test'], loc='upper left')
        plt.show()
        plt.savefig(f'Models\{Ticker}.png')
    return status, predictions[0][0], last_used_price, np.sqrt(
        hist['val_mse'].values[-1])
示例#28
0
 def get_prices(self, stocks):
     p = [round(float(i),2) for i in rs.get_latest_price(stocks)]
     return p
示例#29
0
def priceFloat(ticker):
    currentPrice = rh.get_latest_price(ticker)
    for item in currentPrice:
        currentPrice = float(item)
    return currentPrice
示例#30
0
def latest_price(symbol):
    price = robin_stocks.get_latest_price(symbol)
    print(price)
    return price[0]