Giter VIP home page Giter VIP logo

robinhood-to-csv's Introduction

Robinhood to CSV

A Python script to export your Robinhood trades to a .csv file. Based on the Robinhood library by Rohan Pai. Read the back story on my blog.

Works on Python 2.7+ and 3.5+

Install:

pip install -r requirements.txt

Run:

For exporting stock trades, run:

python csv-export.py

For exporting options trades, run:

python csv-options-export.py

For Device_Token go to your browser

Go to robinhood.com. Log out if you're already logged in
Right click > Inspect element
Click on Network tab
-Enter "token" in the input line at the top where it says "Filter URLs"
With the network monitor-er open, login to Robinhood
You'll see two new urls pop up that say "api.robinhood.com" and "/oauth2/token"
Click the one that's not 0 bytes in size
Click on Headers, then scroll down to the Request Payload section
Here, you'll see new JSON parameters for your login. What you'll need here is the device token.

robinhood-to-csv's People

Contributors

anshu93 avatar jmtoung avatar joshfraser avatar koraykirli avatar martinmelin avatar s-rajaraman avatar savingsandloan avatar tino-247 avatar umer936 avatar utimatu avatar vikkee57 avatar westonplatter avatar wezzybytes avatar yololftw 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

robinhood-to-csv's Issues

experiencing timeouts?

After i input my username/password, it appears the API call is made as I am left hanging for a period of 1-2 minutes. After which I will receive this error:

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.robinhood.com', port=443): Max retries exceeded with url: /api-token-auth/ (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0A3456D0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

Has anyone experienced this and found a fix? I am wondering if it has something to do with my PC, which is behind a corporate proxy.

Fails with Two-Factor Auth

Login fails when two-factor authentication is enabled. I get the message:

Invalid username or password. Try again.

Pulling Information For Assigned Shares Sale

I am trying to use this framework to pull some stats for my personal account, and I am guessing this is a limitation on the underlying API since I see the same problem when viewing the History on the stock but wanted to check. I noticed when trying to do some profit calculations that I occasionally have a missing 100 shares of a stock. I tracked it down to when I was assigned to sell shares on a covered call, that sale is not recorded as a sale of the stock, nor could I discern it from any other sale of a call (where I wasnt assigned).

Thanks
Mike

Robinhood - csv Error

I am receiving this error when running the bat file

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Dividends

Does it also export dividend data?

Thanks,

J

How to bring in MFA info?

>python csv-export.py

Traceback (most recent call last):
  File "csv-export.py", line 53, in <module>
    if logged_in != True and logged_in.get('non_field_errors') == None and logged_in['mfa_required'] == True:
KeyError: 'mfa_required'

KeyError: u'settlement_date

Using Python 2.7.11 on Windows 10 I get the following error after entering my username and password:

Traceback (most recent call last):
File "D:\robinhood-to-csv\csv-export.py", line 63, in
csv += str(fields[row][key]) + ","
KeyError: u'settlement_date'

Csv file format

My tax software wants a csv file with the following format:

name,acquired,sold,proceeds,cost

example:

ALPHABET INC CLASS A COMMON STOCK,10/19/2016,11/03/2016,779.07,824.52
TESLA MOTORS INC,12/02/2016,12/06/2016,1468.19,1460.64

How can I get the output in the csv like this?
Thanks you!

Pandas Utilization

Any objection to utilizing pandas for some of the data manipulation involved here? I am relatively new to working on others GitHubs so I was trying to create a pull request but couldn't figure out how to do it. I have working code already if you'd like to test for yourself! Your code is great otherwise, very helpful!

Getting this error when I try to run either csv-export.py or csv-options-export.py

Robinhood username: Traceback (most recent call last):
File "csv-export.py", line 41, in
logged_in = collect_login_data(robinhood_obj=robinhood, username=username, password=password, device_token=device_token, mfa_code=mfa_code)
File "C:\Users\Josh\Desktop\robinhood-to-csv-master\login_data.py", line 20, in collect_login_data
username = input()
UnboundLocalError: local variable 'input' referenced before assignment

Log-in error

When I am trying to run the csv script, this is what I'm getting:

>>> python csv-export.py 

Traceback (most recent call last):
  File "csv-options-export.py", line 52, in <module>
    if logged_in != True and logged_in.get('non_field_errors') == None and logged_in['mfa_required'] == True:
KeyError: 'mfa_required'

Any ideas on how I can fix this?

IndexError: list index out of range

Using Python 2.7.11 on Windows 10 I get the following error after entering my username and password:

Traceback (most recent call last):
File "D:\robinhood-to-csv\csv-export.py", line 32, in
for key, value in enumerate(executions[0]):
IndexError: list index out of range

password path blocked

After running csv-export.py or csv-options-exprot.py the terminal doesn't let me input/type in my password... anybody else having this issue?

profit_extractor.py runs into ParserError for regular trades

While the run without --profit works without problems, profit calculation is encountering ParserError every time!

$ python csv-export.py --profit
Username:
Password:
MFA:
Generated device token: 

Pulling trades. Please wait...
0 queued trades and 473 executed trades found in your account.
Choose a filename or press enter to save to `robinhood.csv`:

What is your tax multiplier -default 0.25 (25%) ?
Traceback (most recent call last):
  File "D:\python\robinhood-to-csv\csv-export.py", line 238, in <module>
    profit_csv = profit_extractor(csv, filename)
  File "D:\python\robinhood-to-csv\profit_extractor.py", line 20, in profit_extractor
    handle_raw = pd.read_csv(filename)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\io\parsers\readers.py", line 581, in _read
    return parser.read(nrows)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\io\parsers\readers.py", line 1254, in read
    index, columns, col_dict = self._engine.read(nrows)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 225, in read
    chunks = self._reader.read_low_memory(nrows)
  File "pandas\_libs\parsers.pyx", line 805, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 861, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 847, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1960, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 55 fields in line 237, saw 57

Python Info

$ python -V
Python 3.10.4

unable to get login using correct credentials

i removed special characters from my password as i found noted in #5 -- even after doing that, i get the same error as before i changed my password:

Traceback (most recent call last):
File "d:\app\robinhood-to-csv\csv-export.py", line 46, in
logged_in = robinhood.login(username=username, password=password)
File "d:\app\robinhood-to-csv\Robinhood.py", line 81, in login
res = res.json()
File "d:\dev\Python37\lib\site-packages\requests\models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "d:\dev\Python37\lib\json_init_.py", line 348, in loads
return _default_decoder.decode(s)
File "d:\dev\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "d:\dev\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Unable to login using correct credentials

I am unable to login with the csv-export.py script, but I CAN log into robinhood.com using the same credentials. I am certain that I am typing everything correctly!

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Python 3.6.5 on OSX 10.13.6
After entering username and password getting error:
Traceback (most recent call last):
File "csv-options-export.py", line 45, in
logged_in = robinhood.login(username=username, password=password)
File "/Users/jason/Documents/repo/RS/robinhood-to-csv/Robinhood.py", line 81, in login
res = res.json()
File "/Users/jason/Documents/repo/RS/robinhood-to-csv/env/lib/python3.6/site-packages/requests/models.py", line 896, in json
return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0

Py 3 conversion

Just a suggestion to possible create a python 3+ compatible version. Works fine otherwise.

Invalid Input on login

Generated device token: a3de19ea-6d92-11eb-a3d9-448500a61369

Invalid inputs. Please try again.

Robinhood username: 

Entering the right login credentials (double checked) but I keep getting invalid input. Any ideas?

Stop asking for a device_token

Our current instructions for manually grabbing a device_token work but are a bit painful. Looks like we can probably just generate a random one:

securient/Robinhood@95d7dbd

If that doesn't work, we should at least be able to grab one from their API instead of having people dig around in the developer console for it.

Posting this here in case someone gets around to fixing this before me.

csv-export.py Syntax Error

Ran pip install -r requirements.txt in cmd (Microsoft Windows [Version 10.0.16299.309])
Then when I try to run python csv-export.py command, I get this error:

C:\robinhood-to-csv-master>python csv-export.py
  File "csv-export.py", line 36
    print("Robinhood username:", end=' ')
                                    ^
SyntaxError: invalid syntax

Running Python 2.7.12:

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32

Total trade count mismatch

Since the counter only updates if order['state'] == 'filled', it excludes orders that were partially filled before being cancelled.

For example: I have following trade in my portfolio, but it was excluded form the count:

order:{
'updated_at':'[TIMESTAMP]',
'ref_id':'[REF_ID]',
'time_in_force':'gfd',
'fees':'0.00',
'cancel':None,
'response_category':None,
'id':'[ORDER_ID]',
'cumulative_quantity':'5.00000',
'stop_price':None,
'reject_reason':None,
'instrument':'https://api.robinhood.com/instruments/[POSITION_ID]/',
'state':'cancelled',
'trigger':'immediate',
'override_dtbp_checks':False,
'type':'limit',
'last_transaction_at':'[TIMESTAMP]',
'price':'9.00000000',
'executions':[
{
'timestamp':'[TIMESTAMP]',
'price':'9.00000000',
'settlement_date':'[YYYY-MM-DD]',
'id':'[EXECUTION_ID]',
'quantity':'5.00000'
}
],
'extended_hours':False,
'account':'https://api.robinhood.com/accounts/[ACCOUNT_ID]/',
'url':'https://api.robinhood.com/orders/[ORDER_ID]/',
'created_at':'[TIMESTAMP]',
'side':'buy',
'override_day_trade_checks':False,
'position':'https://api.robinhood.com/accounts/[ACCOUNT_ID]/positions/[POSITION_ID]/',
'average_price':'9.00000000',
'quantity':'500.00000'
}

Bug when several executions in an order

When there are several executions within an order, the quantity extracted is wrong because the current code uses the quantity of the first execution.

For example, the CSV will say that the quantity of the order is 100 while it is actually 231.

{
    ...
    'average_price': '1.30000000',
    'cumulative_quantity': '231.00000',
    'price': '1.31000000',
    'quantity': '231.00000', 
    'executions': [
        {'id': 'xxx',
        'price': '1.30000000',
        'quantity': '100.00000',
        'settlement_date': '2015-12-22',
        'timestamp': '2015-12-17T20:19:52.656000Z'},
        {'id': 'yyy',
        'price': '1.30000000',
        'quantity': '100.00000',
        'settlement_date': '2015-12-22',
        'timestamp': '2015-12-17T20:19:52.656000Z'},
        {'id': 'zzz',
        'price': '1.30000000',
        'quantity': '31.00000',
        'settlement_date': '2015-12-22',
        'timestamp': '2015-12-17T20:19:52.657000Z'}],
    ...
}

By removing the 2 following lines, the code will use the quantity of the order which I believe is correct.
https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-export.py#L95-L96

Export Deposits/Withdrawals

Hello, this is a great tool! I've used this as a basis for writing some code to start analyzing my trades.

Just wondering if it is possible to include deposits/withdrawals from our robinhood account or if you have any pointers on how I can add code to access this data.

Thanks

option export file error

I am trying to execute "csv-options-export.py".

Below is the traceback error:

Traceback (most recent call last):
File "csv-options-export.py", line 52, in
if logged_in != True and logged_in.get('non_field_errors') == None and logged_in['mfa_required'] == True:
KeyError: 'mfa_required'

I was able to run "csv-export.py" successfully.

Not compatible with Python 2.7

Your readme states that this is compatible with Python 2.7+, but I found that it is not. In the script is print("Robinhood username:", end=' '). This will fail on 2.7 unless you do an import: from __future__ import print_function.

I am running Python 2.7.14

profit_extractor.py runs into AttributeError for option trades

While the run without --profit works without problems, profit calculation is encountering DataFrame not having certain attribute!

$ python  csv-options-export.py --profit
Username:
Password:
MFA:

Generated device token: 
Pulling trades. Please wait...
0 queued trades and 688 executed trades found in your account.
Choose a filename or press enter to save to `option-trades.csv`:

What is your tax multiplier -default 0.25 (25%) ?
Traceback (most recent call last):
  File "D:\python\robinhood-to-csv\csv-options-export.py", line 164, in <module>
    profit_csv = profit_extractor(csv, filename)
  File "D:\python\robinhood-to-csv\profit_extractor.py", line 23, in profit_extractor
    handle['last_transaction_at'] = pd.to_datetime(handle.last_transaction_at)
  File "D:\python\robinhood-to-csv\env\lib\site-packages\pandas\core\generic.py", line 5575, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'last_transaction_at'

Python Info

$ python -V
Python 3.10.4

in generated csv file, the field name mismatch with value

The field name mismatch with its value. For example in my generated file:

executed_notional | execution_state | extended_hours | fees
{u'currency_id': u'1072fc76-1862-41ab-82c2-485837590762' | u'amount': u'903.80' | u'currency_code': u'USD'} | completed

Never prompts for username and password without command line options

Line 37 - 50 where the conditionals that were looking for empty strings didn't work for me because I didn't specify my username and password on the command line.

The argument parser was looking for empty strings but I had none.

My work around was to remove the conditional prompts and ask for the user name and password as follows (not eloquently):

username = input("Username: ")
password = getpass.getpass()
mfa_code = input("mfa_code: ")

Unable to login

Unable to log in
Error: invalid username pass
Have not enabled 2 factro auth.
I think RH is now sending code on cell to login hence the issue.
Can you please fix ?

TypeError: login() got an unexpected keyword argument 'device_token'

Looks like there is a new issue, I am getting the following when i try to login...

Traceback (most recent call last):
File "csv-options-export.py", line 39, in
logged_in = collect_login_data(robinhood_obj=robinhood, username=username, password=password, device_token=device_token, mfa_code=mfa_code)
File "/Users/JohnVernam/Desktop/robinhood-to-csv-master/login_data.py", line 38, in collect_login_data
logged_in = robinhood_obj.login(username=username, password=password, device_token=device_token)
TypeError: login() got an unexpected keyword argument 'device_token'

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.