joshfraser / robinhood-to-csv Goto Github PK
View Code? Open in Web Editor NEWPython script to export Robinhood trades to a CSV file
License: MIT License
Python script to export Robinhood trades to a CSV file
License: MIT License
When I run python csv-export.py
, it requires me to enter Robinhood device token, which I had no idea what it is.
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
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
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)
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.
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
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'
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 ?
Fix here: #37
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'
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!
Less of an issue. In the App we can watch stocks. Is there a way to pull the stocks we are watching as well?
Login fails when two-factor authentication is enabled. I get the message:
Invalid username or password. Try again.
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!
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
I am receiving this error when running the bat file
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
https://api.robinhood.com/api-token-auth/ results in a 404 error.
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
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: ")
I fixed it in my script using data = urllib.parse.urlencode(fields) based on http://stackoverflow.com/questions/28906859/module-has-no-attribute-urlencode
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
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
>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'
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
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?
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:
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.
Is there any way to download all the ETFs symbols in robinhood?
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
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!
Not an issue with code but How do I correctly open/import the csv file in excel the data is skewed due to json in the data which is also a csv data.
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.
I think it would be helpful to move username and password out of the source code into git ignore config files. Happy to work on this
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
robinhood-to-csv/profit_extractor.py
Line 102 in 4e664be
When q is a float, the range fails. Forcing the q to int solve this bug.
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?
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?
Currently trying to login using my email (RH doesn't use usernames anymore) and I only get invalid inputs. I assume this no longer works?
Just a suggestion to possible create a python 3+ compatible version. Works fine otherwise.
I have tried with and without 2 factor authentication, get the same error regardless. Pulling device token out of Chrome without quotation marks, pasting it, get invalid inputs every time.
Does it also export dividend data?
Thanks,
J
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'
}
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
Line 112 in csv-export.py
( https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-export.py#L112 ).
Also, there is a mixture of tabs and spaces within cdv-export.py
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.