GithubHelp home page GithubHelp logo

robinhood-unofficial / pyrh Goto Github PK

View Code? Open in Web Editor NEW
1.8K 139.0 603.0 714 KB

Python Framework to make trades with the unofficial Robinhood API

Home Page: https://pyrh.readthedocs.io/en/latest/

License: MIT License

Python 98.21% Jupyter Notebook 1.79%
python robinhood-api python-framework

pyrh's Introduction

robinhood-logo


pyrh - Unofficial Robinhood API

Build Status

Coverage

Documentation Status

PyPI Version

PyPI - Downloads

License

Code Style

Help Wanted

Python Framework to make trades with Unofficial Robinhood API. Supports Python 3.8.1+

Please note this project is stable and in maintenance mode but is happy to accept contributions

Documentation: https://pyrh.readthedocs.io/en/latest/

Quick start

from pyrh import Robinhood

rh = Robinhood(username="YOUR_EMAIL", password="YOUR_PASSWORD")
rh.login()
rh.print_quote("AAPL")

How To Install:

pip install pyrh

Clone the repository and install jupyter capabilities.

$ git clone https://github.com/robinhood-unofficial/pyrh.git
$ cd pyrh
$ python --version # python 3.3+ for venv functionality
Python 3.8.1
$ python -m venv pyrh_env
$ source pyrh_env/bin/activate
(pyrh_env) $ pip install .[notebook]
(pyrh_env) $ cp .env.sample .env # update the values in here
(pyrh_env) $ jupyter notebook notebooks/example.ipynb

Now just run the files in the example.

pyrh's People

Contributors

adithyabsk avatar ahaggard2013 avatar anthonykrivonos avatar ciresnave avatar cjbarker avatar dormant-user avatar dsouzarc avatar gitter-badger avatar gregoberfield avatar jammarher avatar jamonek avatar jasonleehodges avatar jeffweng8 avatar jsmwoolf avatar lockefox avatar lordloh avatar milancurcic avatar miserlou avatar mlsmith avatar msk avatar oogali avatar pavpanchekha avatar robertagee avatar rohanpai avatar samueleishion avatar securient avatar supersaiyanmode avatar te12944265-amaha avatar xinwuc avatar zafrinminoti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyrh's Issues

Helper for company metadata

I've been wanting a get_info() function that operates more like pandas-datareader. It's kinda the defacto quick resource for finance for python.

Unfortunately, it requires 3 pulls from Robinhood to mimic the 1 pull from Yahoo

  • /quote: for prices
  • /fundamentals: for company info
  • /instruments: for company name and market info

API Suggestions

Hiya!

You could use the nonzero=true url param/value to get only positions with shares you own rather than stepping through the list in securities_owned.

Add Timeouts to Requests Calls

The python-requests library has a really nasty problem of not setting a default timeout value (related: psf/requests#3070)

Therefore, sometimes random requests get "stuck" (especially with SSL connections), which is problematic for very long-running applications. This library is vulnerable to this problem because it doesn't use a default timeout.

We should add one! I can PR if you accept the idea.

How do I check the current value of a stock

I'm currently using the Yahoo api with pandas datareader which is becoming an issue because it can't read all of the urls for some reason. I need a foolproof method of getting current stock prices and preferably the opening price of the stock as well so I can move forward with my program.

Request Crypto

This isn't really an issue, but any chance that crypto will be implemented? I though that maybe getting the price by treating it like a quote ( something like https://api.robinhood.com/quotes/BTC-USD/ ) would work but it doesn't seem to. I tried finding the appropriate API endpoint but can't seem to figure it out. The mobile app must be accessing it somehow though.

I know that trading is not yet allowed for crypto, but even just getting the price right now would be awesome to get a head start on building a bot! Thanks

AttributeError: 'Transaction' object has no attribute 'name'

Hi, I am new to python. I tried the example code for buy_order or sell_order. Here are the error messages.

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/Joel/PycharmProjects/Robinhood_AI/try_robinhood.py
Traceback (most recent call last):
File "/Users/Joel/PycharmProjects/Robinhood_AI/try_robinhood.py", line 7, in
buy_order = my_trader.place_buy_order(stock_instrument, 1)
File "/Library/Python/2.7/site-packages/Robinhood/Robinhood.py", line 760, in place_buy_order
return self.place_order(instrument, quantity, bid_price, transaction)
File "/Library/Python/2.7/site-packages/Robinhood/Robinhood.py", line 721, in place_order
'side': transaction.name.lower(),
AttributeError: 'Transaction' object has no attribute 'name'

Process finished with exit code 1

Request Limit

This isn't an issue really, well, hopefully not yet. Is there a request limit to the Robinhood API?

If I call trader.quote_data('AAPL') every couple seconds all day, will I eventually get rejected?

HTTPError: 403 Client Error: Forbidden LoginFailed

Login trader appears to be broken?
Did Robinhood change something?

Traceback
(most recent call last):
File "C:\Python3\lib\site-packages\Robinhood\Robinhood.py", line 124, in login
res.raise_for_status()
File "C:\Python3\lib\site-packages\requests\models.py", line 929, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://api.robinhood.com/api-token-auth/

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python3\lib\site-packages\Robinhood\Robinhood.py", line 128, in login
raise RH_exception.LoginFailed()
Robinhood.exceptions.LoginFailed

Standard Authentication "store"

What are the thoughts on having a standard credential store method for this library? In scope? Out?

For example I tried this with the keyring module:

import keyring
import os
keyring.set_keyring( keyring.backends.kwallet.DBusKeyring() )
username = os.getenv('RHUSER',os.getenv('USER'))
password = keyring.get_password('rhAPI', username)

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

https://pypi.python.org/pypi/keyring

Of course not everyone is going to match their local and online usernames as I was, but we could also have a dotFile somewhere with that for example. keyring could also fallback to using a flatfile, but I like to encourage using an encrypted stores.

Consistent + Spacious Formatting

Make the code look more 'Pythonic' and follow more of PEP 8's styleguide.

Add additional spacing + more consistent documentation to increase readability

How do I see what stocks I currently own?

I don't want to be guessing at what stocks I own and which ones I do not. Is there a way that I can enumerate my owned stocks?

Ex. trade.mystocks()
['AAPL', 'MYSE']

Proposal: Exposing the API Error text in exceptions

Throughout the API we use the requests.raise_for_status, however this often hides the API usage hints that Robinhood returns in the content of the error message which makes it harder to troubleshoot. (I'm certain more than a few of us have been confounded by this at times)

I experimented with a few options. One of them being the exception chaining, but that just seemed clumsy, resulted in useless extra traceback and is also only py3 compatible.

I finally ended up with this:

    def raiseForStatus(self,res):
        """Helper for requests.raise_for_status that returns the content as well

            The Robinhood API often returns useful hints about what params are
            out of bounds.  This wrapper helps expose those to the client
            """
        try:
            res.raise_for_status()
        except requests.exceptions.HTTPError as error:
            # HTTPError expected to use args, if it isn't this needs fixing anyway
            if error.args is not None:
                args = error.args
                if error.response.text:
                    apitext = "API Returned: " + error.response.text
                    error.args = args, apitext
            raise

Which results in error messages such as (last line being the addition):

>>> rh.get_historical_quotes('AAPL', interval='day', span='week')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/~/src/Robinhood/Robinhood/Robinhood.py", line 474, in get_historical_quotes
    self.raiseForStatus(res)
  File "/~/src/Robinhood/Robinhood/Robinhood.py", line 121, in raiseForStatus
    res.raise_for_status()
  File "/~/src/Robinhood/py3/lib/python3.4/site-packages/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: (('400 Client Error: Bad Request for url: https://api.robinhood.com/quotes/historicals/?symbols=AAPL&bounds=regular&interval=day&span=week',), 
'API Returned: {"span":["\\\\\\"week\\\\\\" is not a valid choice."]}')

Essentially all calls to res.raise_for_status() would be replaced with:

    self.raiseForStatus(res)

Always more than one way to skin it, but I figured this was a reasonable approach. Let me know your thoughts.

Tests Broken + Travis-CI

Looks like the test-pass is mostly red and hasn't been run against recent changes. Tests will need to be updated to be green and we should add Travis-CI integration to keep future PR's honest.

Add options market information

I was able to grab the following endpoints that I think would be useful to implement. Would be convenient to have pull request #84 merged before I do so. Also, will need to add in the helper endpoint to convert standard tokens to oauth tokens.

Proposal: Convert all monetary and fractional values to Decimal

I'd like to suggest that this library do Decimal conversion internally for any results returned that are monetary or other fractional values.

In my own use I ran into the floating point accuracy issues, and have done this conversion client-side, but it would be cleaner in the library.

No module named bsddb185

I'm having issues running the trade_history_downloader.py script in Ubuntu.
It's working fine in Mac OS but Ubuntu fails to populate the instrument.db (oddly on Mac OS it creates the file as 'instrument.db.db').
The error is
File "/usr/lib/python2.7/bsddb/init.py", line 270, in
return _DeadlockWrap(lambda: self.db[key]) # self.db[key]
TypeError: String or Integer object expected for key, unicode found

If I use the instrument.db (renamed to remove the extra .db) file from Mac I get this error:
File "trade_history_downloader.py", line 51, in
instruments_db = shelve.open('instruments2.db')
File "/usr/lib/python2.7/shelve.py", line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.7/shelve.py", line 227, in init
Shelf.init(self, anydbm.open(filename, flag), protocol, writeback)
File "/usr/lib/python2.7/anydbm.py", line 84, in open
mod = import(result)
ImportError: No module named bsddb185

This is running in virtualenv
Python 2.7.12

pip list :
certifi (2018.1.18)
chardet (3.0.4)
enum (0.4.6)
idna (2.6)
pip (9.0.1)
requests (2.18.4)
Robinhood (1.0.1)
setuptools (38.5.1)
six (1.11.0)
urllib3 (1.22)
wheel (0.30.0)

AttributeError when calling place_buy_order()

buy_order = rb.place_buy_order(gevo_stock, 1)
Traceback (most recent call last):
File "", line 1, in
File "/home/user/.local/lib/python2.7/site-packages/Robinhood/Robinhood.py", line 744, in place_buy_order
return self.place_order(instrument, quantity, bid_price, transaction)
File "/home/user/.local/lib/python2.7/site-packages/Robinhood/Robinhood.py", line 705, in place_order
'side': transaction.name.lower(),
AttributeError: 'Transaction' object has no attribute 'name'

URLLIB has no attribute urlopen

URL Lib won't access the proxies through getproxies and urlopen also does not work. Would appreciate a hand. Python 3.5.1

Installation

Hi

I downloaded all .py files. I obtain this error when I try and run Robinhood.py

C:\Users\flare9x\Anaconda3\envs\first.coint\python.exe C:/Robinhood/Robinhood-master/Robinhood-master/Robinhood/Robinhood.py
Traceback (most recent call last):
File "C:/Robinhood/Robinhood-master/Robinhood-master/Robinhood/Robinhood.py", line 19, in
from . import exceptions as RH_exception
ImportError: cannot import name 'exceptions'

Process finished with exit code 1

This line seems to be the error:

Installation Issues

Am running into following installation issues, any pointers on how to fix them?
Thanks!

$ pip install .
Processing /Users/pkhadloya/Projects/Robinhood
    Complete output from command python setup.py egg_info:
    error in Robinhood setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/01/vqwx6yys6yz690qtzstj1r780000gn/T/pip-xFkVaG-build/
$ pip install requirements.txt
Collecting requirements.txt
/Users/pkhadloya/.pyenv/versions/etl/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/Users/pkhadloya/.pyenv/versions/etl/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Could not find a version that satisfies the requirement requirements.txt (from versions: )
No matching distribution found for requirements.txt```

Methods for volume and avg volume

Hi,

By any chance, will there be methods for volume and avg volume in the near future? If I missed it in the code, please point out the terminology if different.

Thanks!

Add Popularity Endpoint

There appears to be a 'instruments/popularity' API endpoint which drives the "Top Movers" page. I'd love to be able to see this programmatically getting summarized market activity!

Save Authentication Token

Authentication token should be easily saved and should be the preferred method of logging in, at least as the default. This means users don't need to save their usernames and passwords and don't need to enter them with each run.

ModuleNotFoundError: No module named 'exceptions'

Can't run anything because importing Robinhood blows up...

$ python3 poc.py
Traceback (most recent call last):
  File "poc.py", line 4, in <module>
    from Robinhood import Robinhood
  File "/.../venv/lib/python3.6/site-packages/Robinhood/__init__.py", line 4, in <module>
    from Robinhood.Robinhood import Robinhood
  File "/.../venv/lib/python3.6/site-packages/Robinhood/Robinhood.py", line 14, in <module>
    import exceptions as RH_exception
ModuleNotFoundError: No module named 'exceptions'

Additional system information:

$ python3 -VV
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]

Separate functionality

Iโ€™m thinking about splitting up the framework into a format such as main class / helper classes. How does everyone feel about this?

Sent with GitHawk

def instruments returns error

Error Message: "MissingSchema: Invalid URL '': No schema supplied. Perhaps you meant http://?"

This started happening on the 4/4/2018 Commits.

Placing bids

I'm using place_buy_order and giving it there third argument which is bid price. It's not placing the order and waiting for that price. How do I do that?

View current positions

Hi

Is there a way to view current positions? I see nothing in example.py.

I need to check if I hold a position for my trading logic.

Thanks

get_quote function not returning quote

Currently, the get_quote function returns the symbol of the stock instead of the quote, and is implemented like so:

def get_quote(self, stock=''):
        """wrapper for quote_data"""
        data = self.quote_data(stock)
        return data["symbol"]

I believe instead of returning "symbol" attribute for data, it should be returning the "last_trade_price" attribute?

placing order doesn't work

placing order doesn't work.
place_buy_order <-- this module doesn't work; and
what is a unquote module; there isn't no definition about it.

instruments function trying to capitalize a string

instruments = robinhood.instruments(symbol)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Robinhood-1.0.1-py3.6.egg/Robinhood/Robinhood.py", line 193, in instruments
AttributeError: 'float' object has no attribute 'upper'

The instruments function uses a float, but supposed to use a string? Not sure where I'm getting mixed up here.

Question about init

This may be a dumb question. But I confused me a lot. I have clone the project and pip install it. However when running the example.py code, I got TypeError: 'module' object is not callable when initiating class Robinhood. Thank you so much in advance.
Code:

import os
import pandas as pd
from Robinhood import Robinhood
#Setup
my_trader = Robinhood()

Following is the complete error msg:

my_trader = Robinhood()
Traceback (most recent call last):

  File "<ipython-input-50-1abfe0e669f2>", line 1, in <module>
    my_trader = Robinhood()

TypeError: 'module' object is not callable

Orders not being filled?

I am trying to get up and running with this code; apologies if this is an error on my end and not an issue with the codebase.

I tried programmatically ordering one share of a small company a couple minutes after market open today. The order appeared to be successfully placed and I could view it in the app. However, the order was never filled during the day. At the end of the day, 4:00, it appeared to be automatically cancelled. I tried ordering the same shares in-app during the day and the orders were filled successfully.

Is there anything I could be doing wrong to cause the order to show up in-app but not be filled? Thank you.

ResourceWarning when unittesting Robinhood

  • ResourceWarning: unclosed <ssl.SSLSocket fd=6, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('172.16.1.126', 55137), raddr=('107.23.152.151', 443)> warning appears when running my own unittests

  • unittest looks something like this

def test(self):
  m = Robinhood()
  # test the Robinhood methods
  • I was able to fix the ResourceWarning by including session.close inside a del method in the Robinhood class
  • I followed this issue to come to the decision that adding a del method will reduce the possibility of the ResourceWarning from appearing. issue

Not sure if this is an actionable item. The warning was just bothering me.

Add Order Information

Add the ability to gather information on a previous order.
Can be done with:

curl -v https://api.robinhood.com/orders/{order_id}/ \
   -H "Accept: application/json" \
   -H "Authorization: Token a9a7007f890c790a30a0e0f0a7a07a0242354114"

Retrieving Number of Shares Owned

A feature not available in this repo is the ability to retrieve the number of shares owned for a particular stock symbol. I realize this might be related more to the limitations of Robinhood's API, and not this script (which is great by the way). I've poured through most of the endpoints and can't seem to find where this would be located. Any ideas?

Thanks!

Watchlists

This appears to be missing.

I see the API link for it though. Anyone figure out how to get this working?

2FA Login

When trying to login with 2FA enabled, I get the exception "#requires a second call to enable 2FA"

Is there an API sanctioned way to login with 2FA or is it not supported?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.