def rsi_buy(ticker): my_list = rh.account.build_holdings() if my_list.get(ticker) == None : got_it = False close = [] dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries # gets the daily candlesticks for key in dfh: close.append(float(key['close_price'])) data = np.array(close) if(len(close) > rsiPeriod): rsi_list = list(ti.rsi(data,rsiPeriod)) print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1])) print("") if rsi_list[len(rsi_list) - 1] <= 31 and not got_it: # sell the stock less than 32 os.system('python robin_calls.py buy 1 '+ticker) #using the robin_calls module's terminal command from click group got_it = True if rsi_list[len(rsi_list) - 1] >= 69 and got_it: # buy the stock greater than 69 os.system('python robin_calls.py sell 1 '+ticker) got_it = False else: close = [] dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries for key in dfh: close.append(float(key['close_price'])) data = np.array(close) rsi_list = list((ti.rsi(data,rsiPeriod))) print("Ticker: "+ticker) print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1])) print("") print("Number of shares: " + my_list.get(ticker).get('quantity')) print("") if __name__ == "__main__": api = tradeapi.REST(key_id = 'fromAlpacaAPI',secret_key = 'fromAlpacaAPI',base_url = 'https://paper-api.alpaca.markets',api_version = 'v2') clock = api.get_clock() # seperate API to check when the market is open rh.login("email","password",store_session = True) rh.cancel_all_stock_orders() #cancels all the orders that may have been remaining from the previous day print("==================================") while clock.is_open: main() time.sleep(20) for val in rh.account.build_holdings(): print("Ticker: {}".format(val)) print("#:{}".format((rh.account.build_holdings()[val]['quantity'][0]))) """
def get_moving_average(ticker, n): """ Obtains the moving average of from stock historical data :param ticker: The stock to be analyzed :param n: The day range of the moving average that is being obtained (ie 50-day moving average) :return: Pandas df containing the list of moving averages """ # Access data and convert to pandas DataFrame # Note: pd_history and close_prices has the most recent entry at the end (index of -1) history = r.get_historicals( ticker, span='year', bounds='regular') # gets stock historical prices pd_history = pd.DataFrame( history) # transforms data obtained as a dataframe close_prices = pd_history['close_price'].astype( float) # get close market prices dates = pd_history['begins_at'] # gets date of prices # Calculate moving average based off the range i = 0 moving_average = [] while i < len(close_prices) - n + 1: window = close_prices[i:i + n] window_avg = sum(window) / n moving_average.append(window_avg) i += 1 movAvgdf = { 'moving_average(' + str(n) + ')': moving_average, 'date': dates[n - 1:len(dates)] } return pd.DataFrame(movAvgdf)
def rsi(ticker): rsiPeriod = 14 close = [] dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries for key in dfh: close.append(float(key['close_price'])) data = np.array(close) if(len(close) > rsiPeriod): rsi_list = list((ti.rsi(data,rsiPeriod))) #print("Ticker: "+ticker) #print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1])) #print("") if rsi_list[len(rsi_list) - 1] <= 31: #os.system('python robin_calls.py buy 1 '+ticker) #got_it = True return True if rsi_list[len(rsi_list) - 1] >= 69: #os.system('python robin_calls.py sell 1 '+ticker) #got_it = False return True return False
def get_Last_12(inputSymbol): historicals_2 = r.get_historicals(inputSymbol, span='month', bounds='regular') first_value = [] indexes = [] new_list = list(historicals_2) for days in new_list: first_value.append(days.get('begins_at')) for n in range(0, (len(first_value) - 1)): string = first_value[n] if string[11:20] == '19:00:00Z': indexes.append(n) list1 = [] for i in range(0, len(indexes) - 1): string2 = indexes[i] current_dic = new_list[string2] list1.append(float(current_dic.get('close_price'))) Sum_Last_12 = float(sum(list1)) total_number = len(list1) SMA = Sum_Last_12 / total_number print(SMA) return SMA
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') 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 = volatility.bollinger_mavg(price, n=int(n1), fillna=False) sma2 = 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) return cross
def get_historical_prices(cls, ticker_symbol, span='day'): """Takes a single Ticker Symbol to build a list of tuples representing a time_frame and its respective price :param ticker_symbol: single Ticker Symbol :type ticker_symbol: str :param span: width of the history of the selected stock :type: str :return: [list]: (timeframe <datetime.datetime>, price <int>) """ history = robin_stocks.get_historicals(ticker_symbol, span=span) for time_frame in history: time_frame['begins_at'] = cls.__get_time(time_frame['begins_at']) historicals_df = pd.DataFrame(history).astype({ 'open_price': 'float32', 'close_price': 'float32' }) historicals_df['Average'] = historicals_df.apply( lambda row: (row.open_price + row.close_price) / 2, axis=1) historicals_df = historicals_df.rename( columns={ 'begins_at': 'Date', 'open_price': 'Open', 'close_price': 'Close', 'high_price': 'High', 'low_price': 'Low', 'symbol': 'Symbol', 'volume': 'Volume', 'session': 'Session', 'interpolated': 'Interpolated' }) return historicals_df
def getstockinfo(watchlistname): # fetch data from robinhood and parse data into a dictionary structure that stockcontainer can accept for stock in watchlist: week = r.get_historicals(stock, span='week', bounds="regular") month = r.get_historicals(stock, span='month', bounds="regular") year = r.get_historicals(stock, span='year', bounds="regular") fiveyear = r.get_historicals(stock, span='5year', bounds="regular") data = {} data['name'] = str(stock) data[ 'price'] = "Stock created using secondary method - price not supported" data['earnings'] = r.get_earnings(stock) data['events'] = r.get_events(stock) data['fundamentals'] = r.get_fundamentals(stock) x = stockcontainer(stock, data, "f**k off", week, month, year, fiveyear) traj = trajectory(x) x.addtrajectory(traj) stocksArray.append(x)
def run(sc): global enteredTrade global rsiPeriod print("Getting historical quotes") # Get 5 minute bar data for Ford stock historical_quotes = rh.get_historicals("F", span="month", bounds="regular") closePrices = [] #format close prices for RSI currentIndex = 0 currentSupport = 0 currentResistance = 0 for key in historical_quotes["results"][0]["historicals"]: if (currentIndex >= len(historical_quotes["results"][0]["historicals"]) - (rsiPeriod + 1)): if (currentIndex >= (rsiPeriod - 1) and datetime.strptime( key['begins_at'], '%Y-%m-%dT%H:%M:%SZ').minute == 0): currentSupport = 0 currentResistance = 0 print("Resetting support and resistance") if (float(key['close_price']) < currentSupport or currentSupport == 0): currentSupport = float(key['close_price']) print("Current Support is : ") print(currentSupport) if (float(key['close_price']) > currentResistance): currentResistance = float(key['close_price']) print("Current Resistance is : ") print(currentResistance) closePrices.append(float(key['close_price'])) currentIndex += 1 DATA = np.array(closePrices) if (len(closePrices) > (rsiPeriod)): #Calculate RSI rsi = ti.rsi(DATA, period=rsiPeriod) instrument = rh.instruments("F")[0] #If rsi is less than or equal to 30 buy if rsi[len(rsi) - 1] <= 30 and float( key['close_price']) <= currentSupport and not enteredTrade: print("Buying RSI is below 30!") rh.place_buy_order(instrument, 1) enteredTrade = True #Sell when RSI reaches 70 if rsi[len(rsi) - 1] >= 70 and float( key['close_price'] ) >= currentResistance and currentResistance > 0 and enteredTrade: print("Selling RSI is above 70!") rh.place_sell_order(instrument, 1) enteredTrade = False print(rsi) #call this method again every 1 minutes for new price changes s.enter(60, 1, run, (sc, ))
def get_array(ticker): # See above statement, find the past 54 entries and calculate change in price history = r.get_historicals(ticker, span='year', bounds='regular') # gets stock historical prices pd_history = pd.DataFrame(history) # transforms data obtained as a dataframe close_prices = pd_history['close_price'].astype(float) # get close market prices resized_close_prices = np.array(close_prices[len(close_prices) - 54: len(close_prices)]) i = 1 derivative_array = [0] * 53 while i < len(resized_close_prices): derivative_array[i - 1] = resized_close_prices[i] - resized_close_prices[i - 1] i += 1 return derivative_array
def get_spxl_spxs_hist(self, tf="year"): self.api_init() df_dict = {} results = r.get_historicals("SPXL", span=tf) df = pd.DataFrame().from_dict(results) df_dict["SPXL"] = df results = r.get_historicals("SPXS", span=tf) df = pd.DataFrame().from_dict(results) df_dict["SPXS"] = df for x in df_dict: frame = df_dict[x] frame = frame.iloc[::-1].reset_index() frame["close_price"] = pd.to_numeric(frame["close_price"]) frame["low_price"] = pd.to_numeric(frame["low_price"]) frame["high_price"] = pd.to_numeric(frame["high_price"]) frame["open_price"] = pd.to_numeric(frame["open_price"]) frame["volume"] = pd.to_numeric(frame["volume"]) frame['avg_vol'] = pd.Series( np.where( frame.volume.rolling(13).mean() / frame.volume.rolling(8).mean(), 1, 0), frame.index) frame['avg_close_13'] = pd.Series( np.where( frame.close_price.rolling(13).mean() / frame.close_price.rolling(3).mean(), 1, 0), frame.index) frame['avg_close_21'] = pd.Series( np.where( frame.close_price.rolling(21).mean() / frame.close_price.rolling(8).mean(), 1, 0), frame.index) frame['avg_close_55'] = pd.Series( np.where( frame.close_price.rolling(55).mean() / frame.close_price.rolling(21).mean(), 1, 0), frame.index) frame['std_close'] = frame['open_price'] / frame['close_price'] frame['std_high'] = frame['low_price'] / frame['high_price'] frame.to_csv("./hist_data/robinhood_train/" + x + ".txt") return
def find_hammer(ticker): """ Find if the data presented shows a hammer indicator within the past 3 days. """ # Define Data data = pd.DataFrame( r.get_historicals(ticker, span='year', bounds='regular')) np_open = np.array(data['open_price']).astype('float') np_close = np.array(data['close_price']).astype('float') np_high = np.array(data['high_price']).astype('float') np_low = np.array(data['low_price']).astype('float') # Check for downtrend if check_up_down(np_close) != -1: print("No downtrend history, thus no hammer.") return n = -1 while n >= -3: # Check bearish or bullish if np_open[n] < np_close[n]: bullish = True else: bullish = False # Define candlestick real body and shadow length real_body = abs(np_open[n] - np_close[n]) if bullish: upper_shadow = np_high[n] - np_open[n] lower_shadow = np_close[n] - np_low[n] else: upper_shadow = np_high[n] - np_close[n] lower_shadow = np_open[n] - np_low[n] n -= 1 # Define hammer candlestick ratios in percentages up_ratio = 0.05 rb_ratio = 0.3167 low_ratio = 0.6334 # Check hammer requirements total = real_body + upper_shadow + lower_shadow if up_ratio <= upper_shadow / total and \ rb_ratio <= real_body / total and \ low_ratio <= lower_shadow / total: print("Hammer")
def macd(ticker): alist = [] dfh = rh.get_historicals(ticker,'day','regular') for term in dfh: alist.append(float(term['close_price'])) data = np.array(alist) macd, macd_signal, macd_histogram = ti.macd(data,12,26,9) macd_list = macd_histogram index = len(macd_list) if(index > 2): if macd_list[index - 1] > macd_list[index - 2] and macd_list[index - 2] > macd_list[index - 3]: return True else: return False else: return False
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_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)
data['events'] = r.get_events(stock) data['fundamentals'] = r.get_fundamentals(stock) x = stockcontainer(stock, data, "f**k off", week, month, year, fiveyear) traj = trajectory(x) x.addtrajectory(traj) stocksArray.append(x) addmystocks = True blacklist = [] for key, value in stockList.items(): if addmystocks: if key not in blacklist: earnings = r.get_earnings(key) weekraw = r.get_historicals(key, span='week', bounds="regular") monthraw = r.get_historicals(key, span='month', bounds="regular") yearraw = r.get_historicals(key, span="year", bounds="regular") fiveyearraw = r.get_historicals(key, span="5year", bounds="regular") stocksArray.append( (stockcontainer(key, value, earnings, weekraw, monthraw, yearraw, fiveyearraw))) stocknumber = stocknumber + 1 else: print(f'{key} excluded from calculations') if addmystocks: for stock in stocksArray: trajectoryinfo = trajectory(stock)
from datetime import datetime from dateutil import tz import pandas as pd import plotly.express as px import configparser config = configparser.RawConfigParser() configFilePath = '/Users/philipmassey/.tokens/robinhood.cfg' config.read(configFilePath) rhuser = config.get('login', 'user') rhpwd = config.get('login', 'pwd') login = r.login(rhuser, rhpwd) symbol = 'SPG' df = pd.DataFrame(r.get_historicals( symbol, span='week', bounds='regular')) # 'day', 'week', 'year', or '5year'. Default is 'week'. local = utcToLocal(df.iloc[-1:].begins_at.values[-1]) title = '{} {}'.format(symbol, local) #fig = px.line(df, x='begins_at', y='close_price') fig = px.scatter(df, x='begins_at', y='close_price', title="Hide Gaps with rangebreaks") # fig.update_xaxes( # range=[ # dict(bounds=["May 17", "May 18"]) # ] # )
uPass = def loggingIn(userName, passWord): robin_stocks.login(username=userName, password=passWord) # for login info # inputName = input('Username(email): ') # inputPass = input('Password: '******'' while kill != 'kill': kill = input('Stock ticker: ') output = robin_stocks.get_historicals(kill, bounds='regular') dataFrame = pd.DataFrame(output) print(dataFrame) print(dataFrame.columns) volume = dataFrame['volume'] plt.hist(volume, bins=30) plt.show()
startprice = y['close'] for y in x['^GSPC']['prices'][:11]: endprice = y['close'] market_return = (endprice - startprice) / startprice # Calculate expected rate of return expected_ror = riskfreerate + portfolio_beta * (market_return - riskfreerate) # Gather more portfolio information stocksreturn = [] for ticker in row_names: pastprice = r.get_historicals(ticker, 'year') pastprice = pd.DataFrame(pastprice) pastpriceamt = pastprice['close_price'].astype('float').values[0] currprice = r.get_historicals(ticker, 'day') currprice = pd.DataFrame(currprice) currpriceamt = currprice['close_price'].astype('float').values[0] stock_return = (currpriceamt - pastpriceamt) / pastpriceamt stocksreturn.append(stock_return) # Calculate portfolio profit % based on weighted returns stocksreturn = pd.DataFrame(stocksreturn) stocksreturn = stocksreturn.rename(columns={0: "returns"}) stocksreturn['names'] = row_names stocksreturn = stocksreturn.set_index("names") newreturnval = stocksreturn['returns']
import ta as ta from pandas.plotting import register_matplotlib_converters from ta import * from misc import * from tradingstats import * #!!! Fill out username and password username = '******' password = '******' #!!! print("\n----- Logging in under user: "******" -----\n") #Log in to Robinhood login = r.login(username,password) data = r.get_historicals('WFTLF',span='year',bounds='regular') print(data) if not data: print("oh") def get_watchlist_names(): """ Returns: the name of each 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:
def get_RH_dset(symbol, span, note=''): # span \in ['day', 'week', 'month', '3month', 'year', '5year'] return Robinhood_Data(pd.DataFrame(r.get_historicals(symbol, span=span)), symbol, span, note=note)
def print_data(symbols, span): data = r.get_historicals(symbols, span=span) print("\n data for {}, {}:\n".format(str(symbols), span)) print(data) return
def graph(): # the graph data frame ticker = 'MGNX' history = r.get_historicals( ticker, span='year', bounds='regular') # gets stock historical prices pd_history = pd.DataFrame( history) # transforms data obtained as a dataframe close_prices = pd_history['close_price'].astype( float) # get close market prices resized_close_prices = np.array(close_prices[len(close_prices) - 54:len(close_prices) - 1]) derivative_close_prices = ms.get_array(ticker) # ADDED BY CARL df_cross = g.merge_data('MGNX', 50, 200) # x_set = range(len(df)) short_pts = np.array(df_cross.iloc[:, 0]) long_pts = np.array(df_cross.iloc[:, 1]) # plot df df = pd.DataFrame({ 'x_values': range(len(resized_close_prices)), 'Value ($)': resized_close_prices, 'Change in Value': derivative_close_prices, "Short MA": short_pts, "Long MA": long_pts }) plt.plot('x_values', 'Value ($)', data=df, marker='o', markerfacecolor='red', markersize=12, color='skyblue', linewidth=4) plt.plot('x_values', 'Change in Value', data=df, marker='o', color='blue', linewidth=2) plt.plot('x_values', 'Short MA', data=df, color='blue', linewidth=3) plt.plot('x_values', 'Long MA', data=df, color='orange', linewidth=3) # span the plot over the maximum subarray max_subarray = ms.find_max_subarray(derivative_close_prices, 0, len(resized_close_prices) - 1) max_subarray_left = max_subarray[0] # left side max_subarray_right = max_subarray[1] # right side # plot the maximum subarray span plt.axvspan(max_subarray_left, max_subarray_right, color='green', alpha=0.5) # plot a line at where the golden cross occurs # finish graph settings x_label = "Date" plt.xlabel(x_label) plt.ylabel('Value ($)') plt.title('Value and Change in Value With Maximum Subarray Overlay') # plt.plot(x_set, short_pts) # plt.plot(x_set, long_pts) # plt.legend(["Value ($)", "Change in Value", "Short MA Data", "Long MA Data"]) # show legend plt.legend() # show graph plt.show()
import robin_stocks as rs import pandas as pd from bs4 import BeautifulSoup import requests stock = 'TQQQ' rs.login('username', 'password') info = rs.get_historicals(stock, span='year') df = pd.DataFrame(data=info, columns=['close_price']) s = df[-10:] hist = s['close_price'].tolist() hist = [float(i) for i in hist] # Calculates the moving average over the course of a given number of days def moving_average(days): total = sum(hist) return total / days # Fast stochastic measurement def fast_stochastic(): temp_hist = hist cp = hist[-1] l = min(temp_hist) h = max(temp_hist)
def add_gap_up(df): df['gap_up'] = df.apply(lambda row: row['open'] / float( r.get_historicals(row['symbol'], span='year')[-1]['close_price']) - 1, axis=1)