Data Driven Money

Live. Work. Retire. Smart.

How to use Python to Trade Stocks at Robinhood

How to Use Python to Trade Stocks Online

Table of Contents

How to use Python to Trade Stocks at Robinhood

Trading stocks on Robinhood using automated methods with python is about as easy as trading stocks on its now infamous app. With this tutorial, you should be up and trading stocks literally in under 10 minutes. Here is a list of the 3 things you will need:

    1. A web instance of Jupyter Notebook or Google Colab
    2. A Multi-Factor Authentication (MFA) app such as Google Authenticator
    3. A Robinhood account.

Getting Setup

I personally prefer to use Google Colab to execute my python code. Its free, fast and your notebooks can be run from anywhere that you can use Chrome. In fact, I run my notebooks all the time from my phone… especially my Machine Learning notebooks that aid with my trading decisions.

That said, all of this code will work in any python 3 environment you are working with. You will need only two packages to trade stocks on Robinhood with python. They are both available from pypi and are:

    • robin-stocks – This is the main package we will use to interface with Robinhood’s API. This package is very simple to use and appears to be routinely updated which cannot be said for other Robinhood packages. The creator of the package is Joshua M. Fernandes and his website can be found here

    • PyOTP – This package will be used to implement Multifactor Authentication which Robinhood now requires to log in… even when using Python. When setting up MFA please pay close attention… various steps will be required to prepare Robinhood and your authenticator app… if you lose the information you could lose access to your account.

Our first code block will be simply to load up the necessary libraries.

				
					# install robin_stocks into CoLab environment
!pip install robin_stocks
 
# import the required libraries
from robin_stocks import *
import robin_stocks.robinhood as rh
import pyotp

				
			

Preparing to log into Robinhood with Python

The next step is purely for preparation. Robinhood will no longer allow users to log into their accounts using their usernames and passwords when using their API (e.g. when using Python). Thus, the requirement to use Multi-Factor Authentication is mandatory. Be warned that if you are a frequent Robinhood user, all of your logins will now require a username, password and authentication code.

The authentication code can be generated in Python or you can use Google Authenticator when logging into Robinhood through a web browser or on a mobile device. In order to set up MFA complete the following steps:

    1. Login to Robinhood with your username and password

    2. Click ‘Account Menu‘ from the Top Right

    3. Select the ‘Settings‘ option from the Account Menu Dropdown

    4. Click ‘Security and Privacy’ from left navigation pane

    5. Click ‘ Two-Factor Authentication’ from the Security Section

    6. Toggle the switch for ‘Authentication Method: Authenticator App’ to ‘On’

    7. A QR Code will be presented. Click ‘can’t use this‘ . Now a text code will be presented.

    8. Find a place to save this code securely.

    9. Run the following code block with the code provided above. A 6 digit numeric code will be printed.
				
					totp  = pyotp.TOTP("ENTERCODEHERE").now()
print("Current OTP:", totp)

				
			

10. Input the 6 digit code at the Robinhood prompt.

11. A back-up code should be provided by Robinhood. Store this code securely (e.g. written on paper and put in a safe)

Additionally, you can use the original code provided by Robinhood and store it in the Google Authenticator app. The app will generate the same 6 digit code as the python snippet. Use the Authenticator App to login manually in the future when you are using a web browser.

Logging into Robinhood via Python

After setting up Robinhood properly with MFA, the login code using the robin-stocks python package is very simple. Just input your username (e.g. email address) and password into the string placeholders below and execute the code block. Additionally, your authentication code from the last step should be placed in the pyotp.TOTP function.

Jut keep in mind that your credentials are being stored in clear text whether its on Google Colab or on your personal computer. If your notebook is compromised or distributed by accident in any way you may find that your Robinhood account may be compromised. Safeguard this information as you would access to any of your other financial accounts.

				
					totp  = pyotp.TOTP("ENTERCODEHERE").now()
login = rh.login('email@datadrivenmoney.com','Password', mfa_code=totp)

				
			

After the block successfully executes, the Notebook is officially ‘logged in to Robinhood.’

Trading Stocks

Ok, now its time for the fun stuff. So far, we have written next to no code. The trend will continue. Trading stocks with Robinhood is ridiculously simple with Python so take care that any code you execute is actually the transaction you want to happen.

In order to illustrate how to buy a single security let’s buy a few shares of Nokia. The ticker is NOK and at time of writing this article the price is around $5. I have chosen this stock since it seems relatively liquid and its pretty cheap to show a few examples without worrying about the underlying price.

Buying 2 Shares of Nokia (NOK) Using Python via Robinhood

In order to buy just 2 shares of Nokia with ticker symbol NOK the following code is used:

				
					# Buy 2 Shares of Ticker NOK at Market Price
rh.order_buy_market('NOK',2)

				
			

Downloading Your Portfolio from Robin Hood

In order to get a list of the stocks you own, which should now include NOK then the following command will iterate through and pull out the appropriate data:

				
					# Use Robinhood API to grab Our Portfolio
# Then iterate through and print our stocks 
# to the screen
 
portfolio = rh.build_holdings()
for key,value in portfolio.items():
    print(key,value)

				
			

Based on buying 2 shares of NOK above this would be the result of printing your portfolio:

NOK {‘price’: ‘5.910000’, ‘quantity’: ‘2.00000000’, ‘average_buy_price’: ‘5.9150’, ‘equity’: ‘11.82’, ‘percent_change’: ‘-0.08’, ‘equity_change’: ‘-0.010000’, ‘type’: ‘adr’, ‘name’: ‘Nokia’, ‘id’: ‘74330aeb-5329-4571-98c7-cee3480048c3’, ‘pe_ratio’: None, ‘percentage’: ‘-13.40’}

Selling 2 Shares of Nokia (NOK) Using Python via Robinhood

Naturally, the opposite of buying a stock is to sell the stock. The command is straightforward and can be found below.

				
					# Sell 2 Shares of Ticker NOK at Market Price
rh.order_sell_market('NOK',2)

				
			

When we pull our portfolio again using the code a couple of blocks above the result is empty. We have sold all of our stock so there is nothing in our portfolio. There is a way, however, to grab our all of our orders and save them to an excel spreadsheet. Here is a screenshot of the resulting CSV.

 As you can see, both transactions involving Nokia (NOK) are listed. One buy and one sell. The average price that the orders were filled at along with a time stamp are also provided. Unfortunately, it looks like I lost a half penny on each share while trying to make this demonstration.

Excel Output of Robinhood Portfolio Using Python

Types of Orders

 The Robinhood API allows you to conduct all types of orders. Limit orders and options are all available. The functions to make those orders using the robin-stocks Python package can be found here. As a general rule of thumb, it probably isn’t the best long term strategy to place market orders. Stocks or options that aren’t very liquid may get filled at prices that are not in your best interest or even not at all.

A Note on Algorithmic Trading with Robinhood

Over the years I have developed a number of algorithmic trading systems using Machine Learning and AI, however the one piece of information that is required that we haven’t covered is the current price of a security.

Usually, the price or other market data is required to make some type of prediction. I won’t go into detail here, but if this is the strategy you are looking to develop then it is possible to query Robinhood… but I don’t recommend it. There are much better tools to do this.

Using yahoo finance to pull the price of a stock or option is way better and quicker than using Robinhood. Essentially, pull the data and timeframes for a stock, then run your code or algorithm to determine a buying or selling point. After that use the code provided here in this tutorial to make your trade.

Additionally, be separating out your algorithm and data acquisition you become broker agnostic. You can hold securities at multiple brokerage houses and then use python to execute on any one of them. Python is very diverse and widely developed for the use of trading with various APIs. Below is a code snippet that will pull the current price data for the NOK stock and stores it as a Python Dictionary:

				
					# install the yfinance python package if not already
!pip install yfinance 
# import yfinance
import yfinance as yf
# reach our to yahoo and pull stock ticker 'NOK'
NOK = yf.Ticker('NOK')
# access the ASK for NOK and print it out
print(NOK.info['ask'])

				
			

Additionally, historical data is available as well if your goal is to utilize some type of time series model.

				
					NOK.history(period = "10d")
				
			

The results for such a command would look like this:

DataFrame Output of yfinance Robinhood Trading History

The amount and type of data provided by yfinance can be breathtaking but make sure you understand what you are looking at if you are going to be making some type of buy and sell decision through Robinhood with it. The ‘bid’ and ‘ask’ spreads may be different from Robinhood since it is a 0-commission broker (they likely have wider spreads).

Although I have touted the benefits of using yfinance or a third party to seek pricing information, there is a caveat: you are not likely set up to be a High Frequency Trader so don’t try to act like one. You will want to find a quicker and more reliable service to pull pricing information outside of Robinhood, but understand that your ability to make purchases that profit off of jumping into and out of trades quickly is not likely. Using an API to buy and sell stocks and options on Robinhood should be used for trades with longer time horizons.

The Power is Overwhelming

Between the various Machine Learning algorithms available through packages like sci-kit learn, free financial data available through yfinance and the ability to trade using python with Robinhood’s trading platform you will have all the tools necessary to create your own trading bot or just do simple trades.

Whatever you decide to do while trading on Robinhood with Python just make sure you use order limits and monitor your account balance closely in the case something goes haywire. It is always possible that an API update occurs without your knowledge and some package or dependency doesn’t function as expected.

A Brief but Serious Warning

This ‘how to,’ article is written to be accessible to everyone. Whether you are a beginner at Python or know it extremely well, we believe value will be added. A word of caution should, however, should be mentioned.

Trading stocks is a regulated activity that implies real consequences. When you execute a command to buy a stock through the code, you will be conducting a trade of a security. If you stop a code block early or mistype a ticker symbol then the results can lead to unexpected outcomes.

Always double check your code and if you are looking to test something out then do it with a small amount of stock… small enough where the consequences of losing it or being stuck with a stock you do not want doesn’t matter. There are no take backs if you mess it up or do something you weren’t expecting.

Also, keep in mind that Day Trading laws, the Wash-Sale Rule and taxes all apply. You should do your research on what this may mean for your trading activity. If you are looking to eventually set up a trading bot it makes sense to get an idea of what types of fees / taxes might eat into any expected profits. I have written this article as an expression of my opinion. Do your own research before making any type of investment decisions that may impact your financial situation.

Guy Money

As a formally trained Data Scientist I find excitement in writing about Personal Finance and how to view it through a lens filtered by data. I am excited about helping others build financial moats while at the same time helping to make the world a more livable and friendly place.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top