Exemple #1
0
 def getShareData(self, symbol):
     holdings = self.masterFormat(robin_stocks.build_holdings(), "holding")
     stock = None
     for holding in holdings:
         if robin_stocks.get_name_by_symbol(symbol) == holding.get("name"):
             stock = holding
     stock["sell_val"] = str(
         round(
             float(stock.get("average_buy_price")) -
             (float(stock.get("average_buy_price")) * 0.07), 2))
     return stock
    def verify_login(self) -> bool:
        """
        Verify robinhood can login by performing a basic query.
        
        Returns True if it can.
        """
        result = robin_stocks.get_name_by_symbol('aapl')

        if result == 'Apple':
            return True
        else:
            return False
def lambda_handler(event, context):
    """
    Lambda function to return the current positions held in the Robinhood account.
    Using this to test functionality of this whole shebang before I go further.
    
    This is a stripped down version of the robin_stocks.authentication.login function.
    Lambda only allows writing to /tmp directory, so the concept of pickling a file into
    the home directory won't work. Using SSM securestring for non-ephemeral replacement
    because its free (to 40 TPS), encrypted, and SSM is backed by dynamodb so its fast.
    """
    robinhood_credentials = robinhood_creds()

    #Trick robin_stocks into thinking login was successful.
    helper.set_login_state(True)

    #Set the JWT.
    helper.update_session(
        'Authorization',
        '{0} {1}'.format(robinhood_credentials['token_type'],
                         robinhood_credentials['access_token']))

    #Skip verification. Can handle this here if needed.
    #result = robin_stocks.account.get_current_positions()
    result = robin_stocks.get_name_by_symbol('aapl')

    try:
        return {
            'statusCode': 200,
            'body': json.dumps(result, cls=LambdaMessageEncoder),
            'headers': {
                'Content-Type': 'application/json'
            }
        }
    except Exception as e:
        _LOGGER.error(
            'Something went wrong querying Robinhood account. {0}'.format(e))
        return {
            'statusCode':
            500,
            'body':
            json.dumps(
                {
                    'message':
                    'Something went wrong querying Robinhood account. {0}'.
                    format(e)
                },
                cls=LambdaMessageEncoder),
            'headers': {
                'Content-Type': 'application/json'
            }
        }
Exemple #4
0
 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
Exemple #5
0
 def test_name_apple(self):
     name = r.get_name_by_symbol('aapl')
     assert name == "Apple"
Exemple #6
0
 def test_name_by_symbol(self):
     name = r.get_name_by_symbol(self.single_stock)
     assert (name == 'Apple')
     fake_name = r.get_name_by_symbol(self.fake_stock)
     assert (fake_name == '')
Exemple #7
0
import secrets
# Import the Robin Stocks Library, DotEnv, & OS
import robin_stocks as r

# Use the Robin Stocks login function & RH username/password to authenticate
login = r.login(secrets.username, secrets.password)

# Define an array for the final results
final_result = []

# Use the Robin Stocks get_top_100 function to grab a JSON object with the top 100 most popular stocks info
# top_100 = r.get_top_100()
# can specify up or down
biggest_movers_up = r.get_top_movers_sp500('up')
biggest_movers_down = r.get_top_movers_sp500('down')
# print(top_100)

for stock in (biggest_movers_up):
    symbol = stock['symbol']
    price_move = stock['price_movement']
    #description = stock['description']
    print(symbol, ";", r.get_name_by_symbol(symbol), ";", price_move)
    #print(description)

#print(r.get_name_by_symbol('symbol'))
historicalData = r.get_option_historicals(symbol,expirationDate,strike,optionType,span)

dates = []
closingPrices = []
openPrices = []

for item in historicalData['data_points']:
    print(item)
    dates.append(item['begins_at'])
    closingPrices.append(item['close_price'])
    openPrices.append(item['open_price'])


#!!! I made it so it only got the last 30 days but you could delete these lines to get full year.
dates = dates[-30:]
closingPrices = closingPrices[-30:]
openPrices = openPrices[-30:]
#

# change the dates into a format that matplotlib can recognize.
x = [dt.datetime.strptime(d,'%Y-%m-%dT%H:%M:%SZ') for d in dates]

# plots the data.
plt.plot(x, closingPrices, 'ro')
plt.plot(x, openPrices, 'bo')
plt.title("Option price for "+r.get_name_by_symbol(symbol)+" over time")
plt.xlabel("Dates")
plt.ylabel("Price")
plt.show()
Exemple #9
0
 def test_name_by_symbol(self):
     name = r.get_name_by_symbol(self.single_stock)
     self.assertEqual(name, 'Apple')
     fake_name = r.get_name_by_symbol(self.fake_stock)
     self.assertEqual(fake_name, '')
Exemple #10
0
def login():
    #login using the login
    #===============================================
    #u need the 2FA to login whenever it asks
    trader.login(

#checks the balance by loading the account and returning the buying power
def checkBalance():
    #dictionary with all the account data
    dictionary = trader.profiles.load_account_profile()
    return dictionary["buying_power"]

#access the users portfolio
#pulls all the stocks currently owned by the trader
def traderStocks(json, stock):
    dictionary = trader.account.get_current_positions()
    dictDump = {}

    for item in dict:
        i = 1
        if( str(trader.get_name_by_url(item['instrument'])) == str(trader.get_name_by_symbol(stock)[0])):
            dictDump[str(trader.get_name_by_url(item['instrument'])).upper()] = str(i)
            i+=1
    
    return amount
    

#get prices for the past week
##prices are logged every 10 minutes since the market opens
##logs from 9:30am to 4:00pm 
#checks the current time
#calulates the next time it needs to log
#checks if the current time matches the next logging time
#if true then it logs
#if false then it doesn't
def logClosingPrice(json, timeNow, stock):
    #the ticker symbol
    #can be day week year or 5year
    #extended or regular
    #this is all the data for a specific stock for a week
    allDataDictionary = trader.stocks.get_historicals(stock, span = "week", bounds = "regular")

    #parses to get a list with just the closing price
    for i in range(len(allDataDictionary)):
        dataPriceList.append(allDataDictionary[i]["close_price"])


    #opens the json file with the closing prices as per 10 mins
    with open('Pricesper10min.json') as json_file:
        closingPricesWeekDictionary = json.load(json_file)

    #the moving average is calculated every 10 minutes
    #if the current minute is a ten then its time to log
    logNow = False
    currentMinute = timeNow[14:16]
    if (str(currentMinute[1:2]) == "0"):
        logNow = True

    #checks if the time now is the proper logging time
    if (logNow):
        #this will format the date to match the others and then add it to the dictionary
        dateFormated = timeNow[0:16]+":00Z"
        latestPrice = str(trader.get_latest_price(stock))
        closingPricesWeekDictionary[dateFormated] = latestPrice[2:10]
    
    #opens json file with the closing prices
    with open('Pricesper10min.json', 'w') as outfile:
        json.dump(closingPricesWeekDictionary, outfile, indent = 4)

#open the prices per 10 minutes file
#read from the file
#creates a list with all the closing prices
#calculate the moving average for the entire json file
#compile a dictionary with all the moving averages
#export all that data to the moving averages json file
def movingAverage(json):
    #opens the json file with the closing prices as per 10 mins
    with open('Pricesper10min.json') as json_file:
        closingPricesWeekDictionary = json.load(json_file)

    dataPriceList = []
    for key in closingPricesWeekDictionary:
        dataPriceList.append(closingPricesWeekDictionary[key])
    
    datePriceList = []
    for key in closingPricesWeekDictionary:
        datePriceList.append(key)

    #moving average calculation
    SimpleMovingAverageDictionary = {}
    for i in range(len(dataPriceList)-5):
        SMA = 0
        for t in range(i,i+5):
            SMA += float(dataPriceList[t])
        SMA = SMA / 5
        SimpleMovingAverageDictionary[datePriceList[i+5]] = str(SMA)

    #The finished dictionary ready for json dumping
    with open('MovingAverage.json', 'w') as outfile:
        json.dump(SimpleMovingAverageDictionary, outfile, indent = 4)
    
    json_file.close()
    outfile.close()

#checks the time 
#opens the blacklisted dates
#checks if the date is on a blaclisted date
#checks if the time is when the stock market is open
def availableForTrading(timeNow):
    #opens the json file with the blacklisted dates
    with open('BlacklistedDates.json') as json_file:
        blacklistedDatesDictionary = json.load(json_file)
    json_file.close()

    #checks if the stock market is open by making sure it is not a blacklisted date
    for date in blacklistedDatesDictionary:
        if( str(timeNow[0:10]) == str(date) ):
            return False
    
    #checks if time is between 9:30am and 4:00pm
    hourAndMinute = int(timeNow[11:13] + timeNow[14:16])
    if(hourAndMinute < 1430 or hourAndMinute > 2059):
        return False
    else:
        return True

#opens the moving average json file
#opens the latest prices json file
#checks if the last price crosses the last moving average from bottom to top
#if true then buy
def conditionToBuy(json, currentTime, stock, currentStockPrice):
    #opens the json file with the moving average
    with open('MovingAverage.json') as json_file:
        MovingAverageDictionary = json.load(json_file)
    
    #open file to gather the last few prices
    with open('Pricesper10min.json') as json_file:
        Pricesper10min = json.load(json_file)
    
    MovingAverages = []
    lastMovingAveragePrice = 0
    #finds the last moving average price
    for key in MovingAverageDictionary:
        MovingAverages.append(MovingAverageDictionary[key])
    lastMovingAveragePrice = MovingAverages[len(MovingAverages)-1]

    pricesLast10min = []
    for key in MovingAverageDictionary:
        pricesLast10min.append(Pricesper10min[key])
    lastPrice = pricesLast10min[len(pricesLast10min)-1]
    secondTolastPrice = pricesLast10min[len(pricesLast10min)-2]

    if (lastPrice > lastMovingAveragePrice and secondTolastPrice <  lastMovingAveragePrice):
        buy(json, currentTime, stock, currentStockPrice)
        return True
    else:
        return False

def buy(json, currentTime, stock, currentStockPrice):

    #executes the buy operation for the corresponding stock
    trader.orders.order_buy_limit(stock, 1, lastPrice)

    #open file to gather previous trades
    with open('buyLog.json') as json_file:
        Log = json.load(json_file)

    #adds the current time of the log and price and adds it to the list
    #time format 2020-01-11T20:19:00.000000+00:00
    logTime = currentTime[0:19] + "Z"
    Log[logTime] = str(currentStockPrice) 

    #writes to the json file
    with open('buyLog.json', 'w') as outfile:
        json.dump(Log, outfile, indent = 4)

#opens the moving average json file
#opens the latest prices json file
#checks if the last price crosses the last moving average from bottom to top
#if true then buy
def conditionToSell(json, currentTime, stock, currentStockPrice):
    #opens the json file with the moving average
    with open('MovingAverage.json') as json_file:
        MovingAverageDictionary = json.load(json_file)
    
    #open file to gather the last few prices
    with open('Pricesper10min.json') as json_file:
        Pricesper10min = json.load(json_file)
    
    MovingAverages = []
    lastMovingAveragePrice = 0
    #finds the last moving average price
    for key in MovingAverageDictionary:
        MovingAverages.append(MovingAverageDictionary[key])
    lastMovingAveragePrice = MovingAverages[len(MovingAverages)-1]

    pricesLast10min = []
    for key in MovingAverageDictionary:
        pricesLast10min.append(Pricesper10min[key])
    lastPrice = pricesLast10min[len(pricesLast10min)-1]
    secondTolastPrice = pricesLast10min[len(pricesLast10min)-2]

    if (lastPrice > lastMovingAveragePrice and secondTolastPrice <  lastMovingAveragePrice):
        buy(json, currentTime, stock, currentStockPrice)
        return True
    else:
        return False

#
def sell(json, currentTime, stock, currentStockPrice):

    #executes the buy operation for the corresponding stock
    trader.orders.order_sell_limit(stock, 1, lastPrice)

    #open file to gather previous trades
    with open('sellLog.json') as json_file:
        Log = json.load(json_file)

    #adds the current time of the log and price and adds it to the list
    #time format 2020-01-11T20:19:00.000000+00:00
    logTime = currentTime[0:19] + "Z"
    Log[logTime] = str(currentStockPrice) 

    #writes to the json file
    with open('sellLog.json', 'w') as outfile:
        json.dump(Log, outfile, indent = 4)



def main():
    #login first
    login()

    #define the stock we are going to use
    stock = "HEXO"
    
    while (True):
        timeNow = str(zulu.now())

        if(availableForTrading(timeNow)):
            currentStockPrice = trader.stocks.get_latest_price(stock)
            logClosingPrice(timeNow, stock)
            movingAverage(json, stock)



main()
Exemple #11
0
 def getSymbolName(self, symbol):
     return robin_stocks.get_name_by_symbol(symbol)
NOTE: closing prices are plotted in red and opening prices plotted in blue.
Matplotlib also has a candlestick option that you can use.
'''

#!!! Fill out username and password

load_dotenv()
username = os.getenv('RH_USER')
password = os.getenv('RH_PASS')
#!!!

login = r.login(username, password)

#!!! fill out the specific option information
symbol = 'AAPL'
symbol_name = r.get_name_by_symbol(symbol)
expirationDate = '2020-07-02'  # format is YYYY-MM-DD.
strike = 300
optionType = 'call'  # available options are 'call' or 'put' or None.
interval = 'hour'  # available options are '5minute', '10minute', 'hour', 'day', and 'week'.
span = 'week'  # available options are 'day', 'week', 'year', and '5year'.
bounds = 'regular'  # available options are 'regular', 'trading', and 'extended'.
info = None
#!!!

historicalData = r.get_option_historicals(symbol, expirationDate, strike,
                                          optionType, interval, span, bounds,
                                          info)

dates = []
closingPrices = []
Exemple #13
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"]),
            )