Ejemplo n.º 1
0
def test_for_cointegration(X1, X2):
    X1_historical = rb.get_stock_historicals(X1,
                                             interval="hour",
                                             span="month",
                                             info="close_price")
    X2_historical = rb.get_stock_historicals(X2,
                                             interval="hour",
                                             span="month",
                                             info="close_price")
    p = coint(X1_historical, X2_historical)[1]
    if p < 0.01:
        return True
    else:
        return False
Ejemplo n.º 2
0
 def show_chart(self):
     config = get_config()
     span = config['Chart span']
     interval = config['Chart interval']
     historicals = [[[
         float(d['low_price']) * float(ac.info['quantity']),
         float(d['open_price']) * float(ac.info['quantity']),
         float(d['close_price']) * float(ac.info['quantity']),
         float(d['high_price']) * float(ac.info['quantity'])
     ] for d in rs.get_stock_historicals(
         ac.ticker, span=span, interval=interval)] for ac in self.holdings]
     x = np.arange(len(historicals[0]))
     low_price = np.array(
         [sum([t[0] for t in date]) for date in zip(*historicals)])
     open_price = np.array(
         [sum([t[1] for t in date]) for date in zip(*historicals)])
     high_price = np.array(
         [sum([t[3] for t in date]) for date in zip(*historicals)])
     close_price = np.array(
         [sum([t[2] for t in date]) for date in zip(*historicals)])
     try:
         gp.plot(x, open_price, low_price, high_price, close_price,
                 terminal='dumb',
                 title=f'Past {span} | Low: ${round(min(low_price),2)} - ' \
                         f'High: ${round(max(high_price), 2)}',
                 _with='candlesticks', tuplesize=5,
                 unset=['grid','border','xtics','ytics']
                 )
     except:
         click.echo('Install gnuplot to view chart')
Ejemplo n.º 3
0
def write_volatility(data_frame):
    # Gets volatility of a stock (High volatility = greater price fluctuations)
    for index, new_share_info in data_frame.iterrows():
        print('Writing volatility for:', new_share_info['Symbol'])
        calculated_returns = np.zeros(21)
        deviations = np.zeros(21)
        closing_prices = stonks.get_stock_historicals(new_share_info['Symbol'], interval='day', span='3month', info='close_price')

        for num_index, x in enumerate(closing_prices[:21]):
            if num_index != 0:
                calculated_returns[num_index] = np.log(float(x) / prev_x)
            else:
                calculated_returns[num_index] = float(x)
            prev_x = float(x)
            if calculated_returns[num_index] == 0:
                break
            
        if len(calculated_returns) == 21:
            mean = 0
            for x in calculated_returns:
                mean += float(x)
            mean /= len(calculated_returns)
            for num_index, x in enumerate(calculated_returns):
                deviations[num_index] = x - mean
            variance = 0
            for x in deviations:
                variance += x ** 2
            variance /= len(deviations) - 1
            volatility = math.sqrt(variance)
            data_frame.loc[index, 'Volatility'] = volatility
Ejemplo n.º 4
0
def history(symbol, interval, span):
    ui.success(f'\nGetting {interval} stock historicals for {symbol} for the past {span}....\n')
    result = rh.get_stock_historicals(symbol, interval, span)

    for i in result:
        for x in i:
            ui.success(f'{x}: {i[x]}')
        ui.bar()
Ejemplo n.º 5
0
 def test_stock_historicals(self):
     historicals = r.get_stock_historicals(self.single_stock,
                                           interval='hour',
                                           span='day',
                                           bounds='regular',
                                           info=None)
     assert (len(historicals) <= 6)  # 6 regular hours in a day
     historicals = r.get_stock_historicals(self.single_stock,
                                           interval='hour',
                                           span='day',
                                           bounds='trading',
                                           info=None)
     assert (len(historicals) <= 9)  # 9 trading hours total in a day
     historicals = r.get_stock_historicals(self.single_stock,
                                           interval='hour',
                                           span='day',
                                           bounds='extended',
                                           info=None)
     assert (len(historicals) <= 16)  # 16 extended hours total in a day
Ejemplo n.º 6
0
def golden_cross(stockTicker, n1, n2, days, direction=""):
    """Determine if a golden/death cross has occured for a specified stock in the last X trading days

    Args:
        stockTicker(str): Symbol of the stock we're querying
        n1(int): Specifies the short-term indicator as an X-day moving average.
        n2(int): Specifies the long-term indicator as an X-day moving average.
                 (n1 should be smaller than n2 to produce meaningful results, e.g n1=50, n2=200)
        days(int): Specifies the maximum number of days that the cross can occur by
        direction(str): "above" if we are searching for an upwards cross, "below" if we are searching for a downwaords cross. Optional, used for printing purposes

    Returns:
        1 if the short-term indicator crosses above the long-term one
        0 if there is no cross between the indicators
        -1 if the short-term indicator crosses below the long-term one
        False if direction == "above" and five_year_check(stockTicker) returns False, meaning that we're considering whether to
            buy the stock but it hasn't risen overall in the last five years, suggesting it contains fundamental issues
    """
    if (direction == "above" and not five_year_check(stockTicker)):
        return False
    #history = r.get_historicals(stockTicker,span='year',bounds='regular')
    history = r.get_stock_historicals(stockTicker,
                                      span='year',
                                      bounds='regular')
    closingPrices = []
    dates = []
    for item in history:
        closingPrices.append(float(item['close_price']))
        dates.append(item['begins_at'])
    price = pd.Series(closingPrices)
    dates = pd.Series(dates)
    dates = pd.to_datetime(dates)
    sma1 = ta.volatility.bollinger_mavg(price, n=int(n1), fillna=False)
    sma2 = ta.volatility.bollinger_mavg(price, n=int(n2), fillna=False)
    series = [
        price.rename("Price"),
        sma1.rename("Indicator1"),
        sma2.rename("Indicator2"),
        dates.rename("Dates")
    ]
    df = pd.concat(series, axis=1)
    cross = get_last_crossing(df,
                              days,
                              symbol=stockTicker,
                              direction=direction)
    if (cross) and plot:
        show_plot(price,
                  sma1,
                  sma2,
                  dates,
                  symbol=stockTicker,
                  label1=str(n1) + " day SMA",
                  label2=str(n2) + " day SMA")
    return cross
Ejemplo n.º 7
0
def get_lines(symbol, interval, span):
    ui.success(f'\nGetting {interval} stock historicals for {symbol} for the past {span}....\n')
    result = rh.get_stock_historicals(symbol, interval, span)

    price = rh.get_quotes(symbol)[0]['last_extended_hours_trade_price']

    ui.bar()
    print(f"Value: {price}")
    ui.bar()
    df = funcs.make_df(result)
    funcs.get_s_r(df)
    ui.bar()
Ejemplo n.º 8
0
def search_stock(ticker):
    """ Gets historical data and plot for the passed in ticker"""
    stock_data = robin.get_stock_historicals(ticker,
                                             span='week',
                                             bounds='regular')
    searched_stock = pd.DataFrame(stock_data)
    print(searched_stock)
    # switching to floats so pyplot can read the numbers
    column_list = ['close_price', 'high_price', 'low_price', 'open_price']
    for ind in column_list:
        searched_stock[ind] = searched_stock[ind].astype(float)
    # plot the stock
    searched_stock['close_price'].plot(legend=True, figsize=(12, 5))
Ejemplo n.º 9
0
def check_spread(symbols):
    X1 = symbols[0]
    X2 = symbols[1]
    X1_historical = pd.Series(
        rb.get_stock_historicals(X1,
                                 interval="hour",
                                 span="week",
                                 info="close_price"))

    X2_historical = pd.Series(
        rb.get_stock_historicals(X2,
                                 interval="hour",
                                 span="week",
                                 info="close_price"))
    X1_historical = sm.add_constant(X1_historical)
    X1_historical = np.array(X1_historical, dtype=float)
    X2_historical = np.array(X2_historical, dtype=float)
    results = sm.OLS(X2_historical, X1_historical).fit()
    b = results.params[1]
    X1_historical = X1_historical[:, 1]
    length = len(X1_historical)
    spread = X2_historical - b * X1_historical
    spread_mean = np.mean(spread)
    spread_sd = np.std(spread)
    low, high = spread_mean - 20 * spread_sd / length, spread_mean + 20 * spread_sd / length
    lastX1 = X1_historical[-1]
    lastX2 = X2_historical[-1]
    curr_spread = lastX2 - lastX1 * b
    if curr_spread < low:
        print("Sell ", X1, ", Buy ", X2)
        print("Close when ", X2, " - ", b, " * ", X1, " >= ", low)
    elif curr_spread > high:
        print("Sell ", X2, ", Buy ", X1)
        print("Close when ", X2, " - ", b, " * ", X1, " <= ", high)
    else:
        print(X1, " and ", X2, " are in reasonable range.")
    return True
Ejemplo n.º 10
0
def get_history(password, save, ticker, interval, span):
    """get_history - Get a historical data range for a specific stock.
    
    TICKER - The stock symbol, i.e. TSLA.
    
    INTERVAL - 5minute 10minute hour day week.
    
    SPAN - day week month 3month year 5year.

    example - python robincli.py get_history --save TSLA 5minute day

    """
    with open(ACCOUNT_JSON, 'r') as f:
        account = json.load(f)

    if checkpw(password, account['password']):
        # Login Successful
        click.echo("Logged in as " + account['email'] + "\n")
        r.login(account['email'], password)

        data = r.get_stock_historicals(ticker, interval, span)
        df = pd.DataFrame.from_dict(data)
        df = df.drop(['session', 'interpolated', 'symbol'], axis=1)

        echo = {
            '5minute': '5 minute interval data for ',
            '10minute': '10 minute interval data for ',
            'hour': 'hourly data for ',
            'day': 'daily data for ',
            'week': 'weekly data for '
        }

        click.echo("Getting " + echo[interval] + ticker + " from past " +
                   span + "\n")
        print(df.to_string(index=False))

        if save:
            filename = ticker + "_" + interval + "_" + span + ".csv"
            df.to_csv(filename, index=False)

    else:
        # Login Unsuccessful
        click.echo("Incorrect Robinhood Password")
Ejemplo n.º 11
0
def makeCordinates(tickerVal):
    get_data = r.get_stock_historicals(tickerVal, "day", "3month")
    x = []
    y = []
    data = "[{"
    name = ''
    date = 0
    for group in get_data:
        for key, value in group.items():
            if (key == "begins_at"):
                date += 1
                x.append(date)
                data += '"x": "' + str(date) + '",'
            if (key == "close_price"):
                y.append(float(value))
                data += '"y": "' + str(value) + '"}, {'
            if (key == "symbol"):
                name = value
    data += '}]'
    return name, x, y, data
Ejemplo n.º 12
0
def five_year_check(stockTicker):
    """Figure out if a stock has risen or been created within the last five years.
    Args:
        stockTicker(str): Symbol of the stock we're querying
    Returns:
        True if the stock's current price is higher than it was five years ago, or the stock IPO'd within the last five years
        False otherwise
    """
    instrument = r.get_instruments_by_symbols(stockTicker)
    list_date = instrument[0].get("list_date")
    if ((pd.Timestamp("now") - pd.to_datetime(list_date)) <
            pd.Timedelta("5 Y")):
        return True
    fiveyear = r.get_stock_historicals(stockTicker,
                                       span='5year',
                                       bounds='regular')
    closingPrices = []
    for item in fiveyear:
        closingPrices.append(float(item['close_price']))
    recent_price = closingPrices[len(closingPrices) - 1]
    oldest_price = closingPrices[0]
    return (recent_price > oldest_price)
Ejemplo n.º 13
0
def run():
    global rsiPeriod
    global config

    close_prices = []
    currentIndex = 0

    historical_quotes = r.get_stock_historicals(config['symbol'],
                                                interval='5minute',
                                                span='day')
    df = pd.DataFrame(historical_quotes)

    df['close_price'] = df['close_price'].astype(float)

    DATA = np.array(df['close_price'])

    # If it's early in the day there won't be enough records so just
    # use the length of the dataframe isntead
    if (len(DATA) < rsiPeriod):
        rsiPeriod = len(DATA)
        print(
            "rsiPeriod is larger than DATA length, indicator may not be accurate"
        )

    # if DATA.len is < rsiPeriod then rsiPeriod = DATA.len
    rsi = ti.RSI(DATA, timeperiod=rsiPeriod)

    if (rsi[-1] < rsiFloor):
        message = 'RSI ' + str(rsi[-1]) + ' is below ' + str(rsiFloor)
        print(message)
        pync.notify(message, title="Target floor reached")
    elif (rsi[-1] > rsiCeiling):
        message = 'RSI ' + str(rsi[-1]) + ' is above ' + str(rsiCeiling)
        print(message)
        pync.notify(message, title="Target ceiling reached")
    else:
        print("RSI of " + str(rsi[-1]) + " is not in window\n")
        pass
emaDuration1 = 13
emaDuration2 = 26


def get_EMA(currentPrice, priorEMA, emaDuration):
    smoothing = 2
    multiplier = smoothing / (emaDuration + 1)
    ema = (currentPrice * multiplier) + (priorEMA * (1 - multiplier))
    return ema


#End function

for stock in stockList:
    history = rs.get_stock_historicals(stock,
                                       interval='day',
                                       span='5year',
                                       bounds='regular')
    #print(spy)
    priorEMA1 = 0
    priorEMA2 = 0
    for item in history:
        unit = {}
        unit['date'] = item['begins_at']
        unit['open'] = float(item['open_price'])
        unit['close'] = float(item['close_price'])
        if priorEMA1 == 0:
            currentEMA1 = unit['close']
            emaDifference1 = 0
            currentEMA2 = unit['close']
            emaDifference2 = 0
        else:
Ejemplo n.º 15
0
share_data, share_index = stonk_calc.filter_stocks(all_share_data, share_data,
                                                   share_index)

print()
shares = np.zeros(len(share_data))
bought_price = np.zeros(len(share_data))
macd_sma = [] * len(share_data)
stochastic_sma = np.zeros((len(share_data), 3))

past_macd_signal = np.full(len(share_data), 'None')
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],