Пример #1
0
def rh_setup():
    load_dotenv(verbose=True)
    rh_user = os.getenv("ROBINHOOD_USERNAME")
    rh_pass = os.getenv("ROBINHOOD_PASSWORD")
    rh_qr = os.getenv("ROBINHOOD_QR")
    rh = Robinhood()
    rh.login(username=rh_user, password=rh_pass, qr_code=rh_qr)

    return rh
Пример #2
0
    def addRobinhood(self):
        rh = Robinhood()
        if self.RobinHoodUser:

            rh.login(username=self.RobinHoodUser,
                     password=self.RobinHoodPassword)
            rh.print_quote("AAPL")
        else:
            print("You must set your Robinhood passwords up in init")
Пример #3
0
def login():
    load_dotenv()
    try:
        rh = load_session()
    except InvalidCacheFile:
        rh = Robinhood(username=os.getenv("username"),
                       password=os.getenv("password"))
        rh.login()
        dump_session(rh)  # so you don't have to do mfa again
    return rh
Пример #4
0
def login(email: str, password: str, mfa_secret: str) -> Robinhood:
    client = Robinhood(email, password)
    totp = pyotp.TOTP(mfa_secret)

    # We do this, because we don't want to modify the underlying API library
    # excessively to support this. Therefore, we monkey-patch our way to
    # success.
    with mock_stdin(totp.now()):
        client.login()

    return client
Пример #5
0
def test_cancel_bad_order_id():
    """cancel a naughty order id"""
    bad_id = "1234Dx"
    if not LOGIN_OK:
        pytest.xfail("cannot test without valid user/passwd")
    rh_obj = Robinhood()
    rh_obj.login(
        username=CONFIG.get("LOGIN", "username"),
        password=CONFIG.get("LOGIN", "password"),
    )
    with pytest.raises(ValueError):
        rh_obj.cancel_order(bad_id)
Пример #6
0
    def __init__(self, logger: logging.Logger):
        """Authenticates Robinhood object and gathers the portfolio information to store it in a variable.

        Args:
            logger: Takes the class ``logging.Logger`` as an argument.
        """
        rh = Robinhood()
        rh.login(username=env.robinhood_user,
                 password=env.robinhood_pass,
                 qr_code=env.robinhood_qr)
        raw_result = rh.positions()
        self.logger = logger
        self.result = raw_result['results']
        self.rh = rh
Пример #7
0
 def get(self, request):
     #return HttpResponse(request.user.id)
     #env = environ.Env(DEBUG=(bool, False))
     # reading .env file
     #environ.Env.read_env()
     currentUser = Account.objects.get(user=request.user)
     my_trader = Robinhood()
     my_trader.login(username=currentUser.rhoodID,
                     password=currentUser.rhoodPWD,
                     qr_code=currentUser.rhQ)
     data = my_trader.portfolios()
     my_trader.logout()
     return HttpResponse(data)
     context = {}
     return render(request, self.template_name, context)
Пример #8
0
def create_robinhood_instance(username=None, password=None):
    try:
        if not username:
            username = os.getenv("USERNAME")

        if not password:
            password = os.getenv("PASSWORD")

        rh = Robinhood()
        rh.login(username, password)

        return rh
    except Exception:
        logger.error("Failed to login, exiting...")
        sys.exit()
Пример #9
0
def robinhood() -> None:
    """Gets investment details from robinhood API."""
    if not all([env.robinhood_user, env.robinhood_pass, env.robinhood_qr]):
        logger.warning("Robinhood username, password or QR code not found.")
        support.no_env_vars()
        return

    sys.stdout.write("\rGetting your investment details.")
    rh = Robinhood()
    rh.login(username=env.robinhood_user,
             password=env.robinhood_pass,
             qr_code=env.robinhood_qr)
    raw_result = rh.positions()
    result = raw_result["results"]
    stock_value = watcher(rh, result)
    speaker.speak(text=stock_value)
Пример #10
0
    def main(self, stock, action, quantity):
        username = ""
        password = ""

        rh = Robinhood()
        rh.login(username=username, password=password)

        instrument = rh.instruments(stock)[0]

        if (action == "buy"):
            rh.place_buy_order(instrument, quantity)
            self.enteredTrade = True

        if (action == "sell"):
            rh.place_sell_order(instrument, quantity)
            self.enteredTrade = False
Пример #11
0
class RobinhoodHelper:
    def __init__(self):
        self._future_date = date.today() + timedelta(5)

        self._rh = Robinhood()
        self._rh.login(username=USERNAME,
                       password=PASSWORD,
                       qr_code=MFA)

    def fetch_news(self, stock):
        stock_to_search = stock
        clean_stock_list = []
        if(self.is_time_to_reauthenticate(date.today())):
            self._rh.login(username=USERNAME,
                           password=PASSWORD,
                           qr_code=MFA)

        try:
            news = self._rh.get_news(stock_to_search)
            info_results = news["results"]

            for i in info_results:
                stock_price = self.format_decimal_price(stock)
                stock_info = StockInfo(i["uuid"], i["title"], i["source"], i["published_at"],
                                       i["preview_text"].replace("\n\n", ""), i["url"], stock_to_search, stock_price)
                clean_stock_list.append(stock_info)
            print(stock_to_search + " = " + str(clean_stock_list[0]))
        except Exception as e:
            print("Error: ", e, "Occurred.")
            print("Skipping...")
            print()
        return clean_stock_list

    def is_time_to_reauthenticate(self, now):
        if(now == self._future_date):
            self._future_date = date.today() + timedelta(5)
            return True
        return False

    def format_decimal_price(self, stock):
        TWOPLACES = decimal.Decimal(10) ** -2
        price = str(self._rh.last_trade_price(stock)[0][0])

        return str(decimal.Decimal(price).quantize(TWOPLACES))
Пример #12
0
def test_logout(config=CONFIG):
    """make sure logout works"""
    if not LOGIN_OK:
        pytest.xfail("cannot test without valid user/passwd")
    rh_obj = Robinhood()
    assert rh_obj.login(
        username=config.get("LOGIN", "username"),
        password=config.get("LOGIN", "password"),
    )
    assert rh_obj.auth_token is not None
    req = rh_obj.logout()

    assert req.status_code == 200
Пример #13
0
 def rh_pull_orders_history(user_id, passwd):
     pyrh_rb = Robinhood()
     pyrh_rb.login(username=user_id, password=passwd, challenge_type="sms")
     past_orders = RhWrapper.rh_pull_all_history_orders(pyrh_rb)
     # keep past orders in reverse chronological order
     past_orders_sorted = sorted(past_orders, key=itemgetter('last_transaction_at'), reverse=True)
     orders_saved_to_db = 0
     for order in past_orders_sorted:
         # check if order already in db
         if order['state'] == 'filled':
             obj = robinhood_stock_order_history.objects.filter(timestamp=dateutil.parser.parse(order['last_transaction_at']))
             if not obj:
                 obj                 = robinhood_stock_order_history()
                 obj.order_type      = order['side']
                 obj.price           = order['average_price']
                 obj.shares          = order['cumulative_quantity']
                 obj.symbol, name    = RhWrapper.rh_pull_symbol_from_instrument_url(order['instrument'])
                 obj.state           = order['state']
                 obj.timestamp       = dateutil.parser.parse(order['last_transaction_at'])
                 obj.save()
                 orders_saved_to_db = orders_saved_to_db + 1
         else:
             continue
     logging.error('orders_saved_to_db: ' + str(orders_saved_to_db))
Пример #14
0
class RHClient:
    def __init__(self, rh_account: RHAccount):
        self.rh = Robinhood()
        if not self.rh.login(username=rh_account.username,
                             password=rh_account.password,
                             qr_code=rh_account.qr_code):
            raise Exception("Error in logging into robinhood account")

    def get_positions(self):
        response = self.rh.session.get(endpoints.positions()).json()
        res = self.get_full_results(response)

        def get_position(position):
            stock = get_stock_from_instrument_id(
                get_instrument_id_from_url(position['instrument']))
            return {
                'symbol':
                stock,
                'quantity':
                Decimal(position['quantity']),
                'value':
                Decimal(position['quantity']) * get_latest_stock_price(stock)
            }

        positions = [get_position(position) for position in res]

        return positions

    def get_orders(self):
        response = self.rh.session.get(endpoints.orders()).json()
        res = self.get_full_results(response)

        def filter_order(order):
            return len(order['executions']) > 0

        def get_order(order):
            execution = order['executions'][0]
            return {
                'uid':
                order['id'],
                'instruction':
                order['side'],
                'date':
                execution['timestamp'],
                'stock':
                get_stock_from_instrument_id(
                    get_instrument_id_from_url(order['instrument'])),
                'quantity':
                Decimal(order['quantity']),
                'value':
                Decimal(execution['price'])
            }

        return [get_order(order) for order in res if filter_order(order)]

    def get_transfers(self):
        response = self.rh.session.get(endpoints.ach("transfers")).json()
        res = self.get_full_results(response)

        def filter_transfer(transfer):
            return transfer['state'] == 'completed' and (
                transfer['direction'] == 'deposit'
                or transfer['direction'] == 'withdraw')

        def get_transfer(transfer):
            return {
                'uid': transfer['id'],
                'direction': transfer['direction'],
                'amount': Decimal(transfer['amount']),
                'date': transfer['expected_landing_date']
            }

        return [get_transfer(t) for t in res if filter_transfer(t)]

    def get_full_results(self, response):
        res = response['results']
        while response['next'] is not None:
            response = self.rh.session.get(response['next']).json()
            res += response['results']
        return res
Пример #15
0
from pyrh import Robinhood
import numpy as np
import tulipy as ti
import sched
import time
#A Simple Robinhood Python Trading Bot using RSI (buy <=30 and sell >=70 RSI)
#Youtube : Jacob Amaral
# Log in to Robinhood app (will prompt for two-factor)
rh = Robinhood()
rh.login(username="******", password="******")
#Setup our variables, we haven't entered a trade yet and our RSI period
enteredTrade = False
rsiPeriod = 5
#Initiate our scheduler so we can keep checking every minute for new price changes
s = sched.scheduler(time.time, time.sleep)


def run(sc):
    global enteredTrade
    global rsiPeriod
    print("Getting historical quotes")
    # Get 5 minute bar data for Ford stock
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    currentIndex = 0
    for key in historical_quotes["results"][0]["historicals"]:
        if (currentIndex >=
                len(historical_quotes["results"][0]["historicals"]) -
            (rsiPeriod + 1)):
            closePrices.append(float(key['close_price']))
Пример #16
0
def watcher():
    global graph_msg, graph_min, graph_max
    rh = Robinhood()
    rh.login(username=rh_user, password=rh_pass, qr_code=rh_qr)
    raw_result = rh.positions()
    result = raw_result['results']
    shares_total = []
    port_msg = f"Your portfolio ({rh.get_account()['account_number']}):\n"
    loss_output = 'Loss:'
    profit_output = 'Profit:'
    loss_total = []
    profit_total = []
    graph_msg = None  # initiates a variable graph_msg as None for looped condition below
    n = 0
    n_ = 0
    for data in result:
        share_id = str(data['instrument'].split('/')[-2])
        buy = round(float(data['average_buy_price']), 2)
        shares_count = int(data['quantity'].split('.')[0])
        if shares_count != 0:
            n = n + 1
            n_ = n_ + shares_count
        else:
            continue
        raw_details = rh.get_quote(share_id)
        share_name = raw_details['symbol']
        call = raw_details['instrument']
        share_full_name = loads(get(call).text)['simple_name']
        total = round(shares_count * float(buy), 2)
        shares_total.append(total)
        current = round(float(raw_details['last_trade_price']), 2)
        current_total = round(shares_count * current, 2)
        difference = round(float(current_total - total), 2)
        if difference < 0:
            loss_output += (
                f'\n{share_full_name}:\n{shares_count} shares of {share_name} at ${buy} Currently: ${current}\n'
                f'Total bought: ${total} Current Total: ${current_total}'
                f'\nLOST ${-difference}\n')
            loss_total.append(-difference)
        else:
            profit_output += (
                f'\n{share_full_name}:\n{shares_count} shares of {share_name} at ${buy} Currently: ${current}\n'
                f'Total bought: ${total} Current Total: ${current_total}'
                f'\nGained ${difference}\n')
            profit_total.append(difference)
        if graph_min and graph_max:
            graph_min = float(graph_min)
            graph_max = float(graph_max)
            if difference > graph_max or difference < -graph_min:
                time_now = datetime.now()
                metrics = time_now - timedelta(days=7)
                numbers = []
                historic_data = (rh.get_historical_quotes(
                    share_name, '10minute', 'week'))
                historical_values = historic_data['results'][0]['historicals']
                for close_price in historical_values:
                    numbers.append(round(float(close_price['close_price']), 2))
                fig, ax = plt.subplots()
                if difference > graph_max:
                    plt.title(
                        f"Stock Price Trend for {share_full_name}\nShares: {shares_count}  Profit: ${difference}"
                    )
                elif difference < graph_min:
                    plt.title(
                        f"Stock Price Trend for {share_full_name}\nShares: {shares_count}  LOSS: ${-difference}"
                    )
                plt.xlabel(
                    f"1 Week trend with 10 minutes interval from {metrics.strftime('%m-%d %H:%M')} to "
                    f"{time_now.strftime('%m-%d %H:%M')}")
                plt.ylabel('Price in USD')
                ax.plot(numbers, linewidth=1.5)
                if not path.isdir('img'):
                    mkdir('img')
                fig.savefig(f"img/{share_full_name}.png", format="png")
                plt.close(
                )  # close plt to avoid memory exception when more than 20 graphs are generated
                # stores graph_msg only if a graph is generated else graph_msg remains None
                if not graph_msg:  # used if not to avoid storing the message repeatedly
                    graph_msg = f"Attached are the graphs for stocks which exceeded a profit of " \
                                f"${graph_max} or deceeded a loss of ${graph_min}"
        elif not graph_msg:  # used elif not to avoid storing the message repeatedly
            graph_msg = "Add the env variables for <graph_min> and <graph_max> to include a graph of previous " \
                        "week's trend."

    lost = round(fsum(loss_total), 2)
    gained = round(fsum(profit_total), 2)
    port_msg += f'The below values will differ from overall profit/loss if shares were purchased ' \
                f'with different price values.\nTotal Profit: ${gained}\nTotal Loss: ${lost}\n'
    net_worth = round(float(rh.equity()), 2)
    output = f'Total number of stocks purchased: {n}\n'
    output += f'Total number of shares owned: {n_}\n\n'
    output += f'Current value of your total investment is: ${net_worth}\n'
    total_buy = round(fsum(shares_total), 2)
    output += f'Value of your total investment while purchase is: ${total_buy}\n'
    total_diff = round(float(net_worth - total_buy), 2)
    if total_diff < 0:
        output += f'Overall Loss: ${total_diff}'
    else:
        output += f'Overall Profit: ${total_diff}'
    yesterday_close = round(float(rh.equity_previous_close()), 2)
    two_day_diff = round(float(net_worth - yesterday_close), 2)
    output += f"\n\nYesterday's closing value: ${yesterday_close}"
    if two_day_diff < 0:
        output += f"\nCurrent Dip: ${two_day_diff}"
    else:
        output += f"\nCurrent Spike: ${two_day_diff}"
    if not graph_msg:  # if graph_msg was not set above
        graph_msg = f"You have not lost more than ${graph_min} or gained more than " \
                    f"${graph_max} to generate a graph."

    return port_msg, profit_output, loss_output, output, graph_msg
Пример #17
0
from pyrh import Robinhood
import pyotp
from datetime import datetime
from stock_helper import StockHelper
import unittest
import sys
from dotenv import load_dotenv
load_dotenv(override=True)

MFA = os.getenv("MFA")
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")

rh = Robinhood()
rh.login(username=USERNAME,
         password=PASSWORD,
         qr_code=MFA)


def fetch_news(stock):
    stock_to_search = stock
    clean_stock_list = []
    try:
        news = rh.get_news(stock_to_search)
        info_results = news["results"]
        for i in info_results:
            stock_info = StockInfo(i["uuid"], i["title"], i["source"], i["published_at"],
                                   i["preview_text"].replace("\n\n", ""), i["url"], stock_to_search, "0.00")
            print(str(stock_info))
            clean_stock_list.append(stock_info)
    except Exception as e:
Пример #18
0
    If it's lower than some threshold, it will automatically sell 
"""

import sys, time

sys.path.append('./pyrh')
from pyrh import Robinhood

from dotenv import load_dotenv
load_dotenv()
import os
USERNAME = os.getenv("RH_USERNAME")
PASSWORD = os.getenv("RH_PASSWORD")

rh = Robinhood(username=USERNAME, password=PASSWORD)
rh.login()

# Set how much you're willing to loss
PRICE_DIFF_LIMIT = -100

# How many seconds to wait before polling
REFRESH_TIME = 1800


def fetch_json_by_url(rh, url):
    return rh.session.get(url).json()


def get_current_positions(rh):
    positions = rh.positions()
Пример #19
0
import boto3
import pytz
import requests
from pyrh import Robinhood

from aws_client import AWSClients

current_time = datetime.now(pytz.timezone('US/Central'))
dt_string = current_time.strftime("%A, %B %d, %Y %I:%M %p")

robinhood_user = AWSClients().robinhood_user()
robinhood_pass = AWSClients().robinhood_pass()
robinhood_qr = AWSClients().robinhood_qr()
rh = Robinhood()
rh.login(username=robinhood_user,
         password=robinhood_pass,
         qr_code=robinhood_qr)
raw_result = rh.positions()
result = raw_result['results']


def market_status():
    url = requests.get('https://www.nasdaqtrader.com/trader.aspx?id=Calendar')
    today = date.today().strftime("%B %d, %Y")
    if today in url.text:
        # doesn't return anything which exits the code
        print(f'{today}: The markets are closed today.')
    else:
        # you can return any random value but it should return something
        return True
Пример #20
0
        "symbol": symbol,
        "date": order["last_transaction_at"],
        "state": order["state"],
    }


def get_all_history_orders(rb_client):
    orders = []
    past_orders = rb_client.order_history()
    orders.extend(past_orders["results"])
    while past_orders["next"]:
        print("{} order fetched".format(len(orders)))
        next_url = past_orders["next"]
        past_orders = fetch_json_by_url(rb_client, next_url)
        orders.extend(past_orders["results"])
    print("{} order fetched".format(len(orders)))
    return orders


rb = Robinhood()
# !!!!!! change the username and passs, be careful when paste the code to public
rb.login(username="******", password="******")
past_orders = get_all_history_orders(rb)
instruments_db = shelve.open("instruments.db")
orders = [order_item_info(order, rb, instruments_db) for order in past_orders]
keys = ["side", "symbol", "shares", "price", "date", "state"]
with open("orders.csv", "w") as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(orders)
Пример #21
0
from pyrh import Robinhood
from datetime import datetime
import numpy as np
impor tulipy as ti
import sched
import time

#A Simple Robinhood Python Trading Bot using RSI (buy <=30 and sell >=70 RSI) and with support and resistance.
#Youtube : Jacob Amaral
# Log in to Robinhood app (will prompt for two-factor)
rh = Robinhood()
rh.login(username="******", password="******")

#Setup our variables, we haven't entered a trade yet and our RSI period
enteredTrade = False
rsiPeriod = 5

#Initiate our scheduler so we can keep checking every minute for new price changes
s = sched.scheduler(time.time, time.sleep)

def run(sc):
    global enteredTrade
    global rsiPeriod
    print("Getting historical quotes")
    # Get 5 minute bar data for Ford stock
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    currentIndex = 0
    currentSupport  = 0
    currentResistance = 0
Пример #22
0
parser.add_argument('--percent',
                    type=float,
                    help='Trailing percent',
                    required=False,
                    default=3)
#parser.add_argument(
#    '--tight', type=float, help='Trailing percent when below average price', required=False, default=2)
# Array for all arguments passed to script
args = parser.parse_args()
# Assign args to variables
#    server = args.server

#pprint(args)
#
rh = Robinhood()
logged_in = rh.login(username=args.username, password=args.password)
account = rh.get_account()


def load_positions():
    _pos = {}
    _ord = {}
    next = rh.endpoints['positions'] + '?nonzero=true'
    while True:
        positions = rh.session.get(next).json()
        for position in positions.get('results'):
            instrument = rh.session.get(position['instrument']).json()
            _pos[instrument['symbol']] = position
            _ord[instrument['symbol']] = list(
                filter(
                    lambda x: x['side'] == 'sell' and x['cancel'] != None,
Пример #23
0
from twilio.rest import Client

from lib.aws_client import AWSClients
from lib.emailer import Emailer

start_time = time.time()
now = datetime.now() - timedelta(hours=5)
dt_string = now.strftime("%A, %B %d, %Y %I:%M %p")
print(f'\n{dt_string}')

u = AWSClients().user()
p = AWSClients().pass_()
q = AWSClients().qr_code()

rh = Robinhood()
rh.login(username=u, password=p, qr_code=q)

print('Gathering your investment details...')


def account_user_id():
    ac = rh.get_account()
    user = ac['account_number']
    return user


def watcher():
    global graph_msg
    acc_id = account_user_id()
    raw_result = (rh.positions())
    result = raw_result['results']
Пример #24
0
import os
from pyrh import Robinhood
import sched
import time

USERNAME = os.environ('USERNAME')
PASSWORD = os.environ('PASSWORD')
# Log in to Robinhood app (will prompt for two-factor)
rh = Robinhood()
rh.login(username=USERNAME, password=PASSWORD)
#Setup our variables
traded = False
s = sched.scheduler(time.time, time.sleep)
def run(sc):
    global traded

    # Get historical close price data for the past year
    close_prices = []
    print("Getting historical quotes")
    historical_quotes = rh.get_historical_quotes("F", "day", "year")
    for key in historical_quotes["results"][0]["historicals"]:
        close_prices.append(float(key['close_price']))
    close_prices.reverse()

    # Calculate Simple Moving Average for 50 and 200 days
    sma50 = 0
    sma200 = 0
    for i in range(200):
        print(i)
        if i < 50:
            sma50 += close_prices[i]
Пример #25
0
from pyrh import Robinhood
from datetime import datetime
import numpy as np
import tulipy as ti
import sched
import time
#A Simple Robinhood Python Trading Bot using RSI (buy <=30 and sell >=70 RSI) and with support and resistance.

# Log in to Robinhood app (will prompt for two-factor)
rh = Robinhood()
rh.login(username="******", password="******")
#Setup our variables, we haven't entered a trade yet and our RSI period
enteredTrade = False
rsiPeriod = 5
#Initiate our scheduler so we can keep checking every minute for new price changes
s = sched.scheduler(time.time, time.sleep)


def run(sc):
    global enteredTrade
    global rsiPeriod
    print("Getting historical quotes")
    # Get 5 minute bar data for Ford stock
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    currentIndex = 0
    currentSupport = 0
    currentResistance = 0
    for key in historical_quotes["results"][0]["historicals"]:
        if (currentIndex >=
from pyrh import Robinhood
from datetime import datetime
import numpy as np
import tulipy as ti
import sched
import time
#A Simple Robinhood Python Trading Bot using RSI (buy <=30 and sell >=70 RSI) and with support and resistance.
#Youtube : Jacob Amaral
# Log in to Robinhood app (will prompt for two-factor)
rh = Robinhood()
rh.login(username="******", password="******")
#Setup our variables, we haven't entered a trade yet and our RSI period
enteredTradeq = input("Have you entered trade [y/n]?\n")
if enteredTradeq == "y" or enteredTradeq == "Y":
    enteredTrade = True
    lastBuyPrice = input("What is your last buy price?\n")
    lastBuyPrice = float(lastBuyPrice)
else:
    enteredTrade = False
rsiPeriod = 5
symbol = input("Please enter Stock Symbol?\n")
stockQuantity = input("How many quantity for trading?\n")
#Initiate our scheduler so we can keep checking every minute for new price changes
s = sched.scheduler(time.time, time.sleep)


def run(sc):
    global enteredTrade
    global rsiPeriod
    global lastBuyPrice
    global lastSellPrice
Пример #27
0
                    price
                ]

    @classmethod
    def formatter(cls, stocks_dict: dict) -> dict:
        """Triggers the stock checker and formats the SMS into a dictionary.

        Returns:
            dict:
            Returns a dictionary of ``{stock_ticker: [SMS_text, price]}``
        """
        if (rh_user := environ.get('robinhood_user')) and \
                (rh_pass := environ.get('robinhood_pass')) and \
                (rh_qr := environ.get('robinhood_qr')):
            # noinspection PyUnboundLocalVariable
            rh.login(username=rh_user, password=rh_pass, qr_code=rh_qr)
            print(
                f"\033[32m{prefix(level='INFO')}Using Robinhood's secure session to monitor watchlist.\033[00m"
            )
            source = cls.robinhood
        else:
            print(
                f"\033[32m{prefix(level='INFO')}Using YFinance open session to monitor watchlist.\033[00m"
            )
            source = cls.yfinance

        data_dict = {}
        for key, value in stocks_dict.items():
            if len(value) < 2:
                continue
            if isinstance(value, list):
Пример #28
0
from pyrh import Robinhood
import numpy as np
import tulipy as ti
import sched, time
# Log in to app (will prompt for two-factor)
rh = Robinhood()
rh.login(username="******",
         password="******")
enteredTrade = False
s = sched.scheduler(time.time, time.sleep)


def run(sc):
    global enteredTrade
    print("Getting historical quotes")
    # do your stuff
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    for key in historical_quotes["results"][0]["historicals"]:
        closePrices.append(float(key['close_price']))
    DATA = np.array(closePrices)
    #Calculate RSI
    rsi = ti.rsi(DATA, period=5)
    instrument = rh.instruments("F")[0]
    #If rsi is less than or equal to 30 buy
    if rsi[len(rsi) - 1] <= 30 and not enteredTrade:
        enteredTrade = True
        rh.place_buy_order(instrument, 1)
    #Sell when RSI reaches 70
    if rsi[len(rsi) - 1] >= 70 and enteredTrade:
Пример #29
0
class TheHood:
    """
    A wrapper for producing the kinds of transactions and calls on my Robinhood
    portfolio I'm looking for.
    """
    def __init__(self, credentials: str) -> None:
        self._ext_equity = 0.0

        # Set up connection to Robinhood's API.
        self._rh = Robinhood()
        self._rh.login(**read_credentials(credentials))

    @property
    def extended_hours_equity(self) -> float:
        """
        Keep track of the extended equity and prevent its setting to NoneType.

        Returns:
            The current extended equity.
        """
        return self._ext_equity

    @extended_hours_equity.setter
    def extended_hours_equity(self, new_equity: Union[float, None]) -> None:
        """
        Keep track of the extended equity and prevent its setting to NoneType.

        Returns:
            The current extended equity.
        """
        if type(new_equity) is not float:
            pass
        else:
            self._ext_equity = new_equity

    @retry
    def total_dollar_equity(self) -> Tuple[float, float, float]:
        """
        Get values that explain the current monetary value of my account.

        Returns:
            A tuple containing today's closing equity in my account, followed by the
            previous day's closing value and the current extended / after-hours value.
        """
        self.extended_hours_equity = self._rh.extended_hours_equity()
        return self._rh.equity(), self._rh.equity_previous_close(
        ), self.extended_hours_equity

    @retry
    def account_potential(self) -> float:
        """
        Get the total account potential for comparison against the total account value.
        I define account potential as the sum of all stocks' current worth plus the
        absolute value of any losses.

        Returns:
            A float representing the account potential.
        """
        stocks = self._rh.securities_owned()['results']
        potential_sum = float(self._rh.portfolios()['withdrawable_amount'])
        for stock in stocks:
            # Make quantity a float as the API may change when I buy fractional shares.
            quantity = float(stock['quantity'])
            buy_price = float(stock['average_buy_price'])
            potential_sum += quantity * buy_price
        return potential_sum

    @retry
    def dividend_payments(self, since: str = '') -> float:
        """
        If there are dividend payments, I want to graph a sum in Grafana.

        Args:
            since: the date since we should allow the summation of dividends. For
                   instance, you may wish to set this to the past year.

        Returns:
            A float representing the sum of dividend payments to my account.
        """
        dividends: Dict = self._rh.dividends()['results']
        dividend_sum = 0.0
        for dividend in dividends:
            if dividend['state'] == 'paid':
                if since and not (datetime.fromisoformat(
                        dividend['paid_at'][:-1]) >
                                  datetime.fromisoformat(since)):
                    continue
                dividend_sum += float(dividend['amount'])
        return dividend_sum
Пример #30
0
from pyrh import Robinhood
from dotenv import load_dotenv
import os, time, SendEmail
from timeloop import Timeloop
from datetime import timedelta
import logging

load_dotenv()

tl = Timeloop()
rh = Robinhood()
rh.login(username=os.getenv('ROBINHOOD_USERNAME'),
         password=os.getenv('ROBINHOOD_PASSWORD'),
         challenge_type='sms')
logging.basicConfig(filename='app.log',
                    filemode='w',
                    format='%(name)s - %(levelname)s - %(message)s')


@tl.job(interval=timedelta(seconds=45))
def sendEmailAboutNews():
    t = time.localtime()

    if t.tm_hour == 15 and t.tm_min == 30:
        SendEmail.sendEmail(rh.adjusted_equity_previous_close(), rh.equity())
    else:
        logging.warning('{}: still running'.format(time.strftime(
            "%H:%M:%S", t)))


if __name__ == "__main__":