Analyze Data and Trade Stocks Through Your Browser Using Google Colab and Alpaca API

Hitoshi Harada
Automation Generation
7 min readAug 27, 2019

Alpaca is making it easier to trade stocks programmatically, with zero commission by providing modern REST API. In fact, everyday, we are seeing new people coming in and start trading stocks in a fully- or semi-automated fashion quickly, and I am still getting quite a bit of interest in Google Sheet stock trading example. Yet, it can be a bit of work to set up your programming environment before you can begin playing with API and get any benefit from it, especially when it comes to python which has complicated ecosystems to choose from.

There is actually a solution to this today. You don’t need to worry about messing up with python 2 vs 3, installing code editor, or even opening terminal. All you need is the latest browser such as Chrome and Firefox. Using Google Colab, not only can you start trading with Alpaca API instantly after getting API key, but also you have powerful tools to analyze and visualize data to help you make your trading decisions.

What is Google Colab (used to be called Colaboratory)?

Google Colab is a service that allows you to run Python Jupyter Notebook in the cloud, where you can write any python program from your browser. All you need is your Google account. It manages computing resources in their cloud. The primary use case of the service is machine learning and artificial intelligence research to boost the community. It is a good environment to train your machine learning model with dataset (you can connect your Google Drive to save the training data and models too), and this is also a good service for quantitative finance area where you need to run some python and analyze market data, make quick decisions and trade directly based on the data.

Alpaca API

Alpaca provides commission-free stock trading service with modern Web API. Lots of people are using the service today to automate their own quantitative trading strategies. It comes with the online documents that make it easier to start and open source libraries that you can use out of box in various languages, including python. You can also read examples in Medium and join the community slack and forum to get to know other alike people and gain knowledge from them. You can sign up with email and get the API key for paper trading simulation.

Let’s Get Started

Once you get Alpaca API key from the dashboard, go to Colab. From File, choose “New Python 3 notebook”

It will open a new notebook. A notebook open in your browser automatically connects to the backend execution process that stays with you, starting fresh python 3 environment. The first thing you need to do is install Alpaca Python SDK. Type this in the first code black and click on the run button.

!pip install alpaca-trade-python

It will install the client library in a moment.

Let’s check if it’s installed correctly. Type this in the next code block, replacing YOUR_API_KEY_ID and YOUR_API_SECRET_KEY with your own from dashboard.

import alpaca_trade_api as alpacaapi = alpaca.REST(‘YOUR_API_KEY_ID’, ‘YOUR_API_SECRET_KEY’, ‘https://paper-api.alpaca.markets/’)

If no error is reported, you are good to go!

Submit an Order

There are a number of methods in Alpaca Trading API. Account API gives you the account information such as the current cash and equity balances, while Position API returns the open positions with average entry prices (avg_entry_price) and the number of shares (qty). But of course, in order to see how it works, we have to buy something first using Order API.

In order to get the account information, click on “+Code” from the top menu and type api.get_account() in the new box, then run (you can type Shift+Enter instead of click on the Run button too).

api.get_account()

If you get an error here, make sure you are setting the URL to the right API endpoint and keys are correctly pasted.

Once you know how much money you have, let’s buy one share of Apple as an example. Open a new code block, type this and run.

api.submit_order(‘AAPL’, side='buy' qty=1, type=’market’, time_in_force=’gtc’)

If you are doing this during regular market hours (9:30am — 4:00pm ET), you will get the order filled immediately and see it in list_positions()

api.list_positions()

Otherwise, the order is queued for the next trading day, so you will see it in List Orders endpoint.

api.list_orders()

Easy?

Draw Candlestick Chart

You can now view your account information and place orders via API. One of the benefits to use API for stock trading is that you can make decisions based on the data. Alpaca API also provides market data and you can get it the same way as you retrieve the account information. get_barset() is a function with a number of parameters to filter the data.

api.get_barset(‘AAPL’, ‘day’, limit=10).df

Alpaca Python SDK automatically converts the result JSON to Pandas DataFrame if you use the df property. The notebook will show the tabular format of this.

But it may still be hard to interpret, right? Let’s visualize this data more graphically. In order to do so, you need to install another library called mpl_finance.

!pip install mpl_finance

Then paste this snippet to draw candlestick chart.

from mpl_finance import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import MONDAY, DateFormatter, DayLocator, WeekdayLocator
df = api.get_barset(‘AAPL’, ‘day’, limit=253).df[‘AAPL’]
quotes = zip(mdates.date2num(df.index.to_pydatetime()),
df.open, df.high, df.low, df.close)
fig, ax = plt.subplots(figsize=(20,10))
ax.xaxis_date()
ax.autoscale_view()
alldays = DayLocator()
ax.xaxis.set_minor_locator(alldays)
candlestick_ohlc(ax, quotes, width=0.5, colorup=’g’, colordown=’r’)

Bravo!

Advanced Ideas: Trading with AI/Machine Learning Using GPU

Some say data is new money. You can probably think of many different ways of using market data to make trade decisions in real-time. Calculate indicators of your own and find your top stocks to buy out of thousands of stocks? Sure. Calculate linear regression from the historical price movement to try and predict the future price? Sure. One of the great things in this Google Colab is that it comes with GPU, for free! In fact, lots of researchers are using this platform to experiment their AI models training with GPU. If you are interested, you can further research on how to use Tensorflow or PyTorch in this environment and build your AI trading bot.

Because the designed use case is data mining and machine learning, this environment can execute a long running process, too. If you keep the browser open and start a long running function, it will run up to 12 hours. Do you know how many hours are the trading hours in a day for a regular market session? It’s 6.5 hours. (Though I haven’t tried,) you could potentially run your trading algorithm for the full regular market session, too! Again, you don’t need to install anything in your computer, just open your browser for this service!

I have shown you how to get started with Alpaca API with zero python setup using Google Colab. It is great that there are combined services today that allow you to achieve what was so hard to do before. I have saved the notebook used here in my github and you can even load the notebook as is to your own. We participate on our Forum and our Slack Community so feel free to reach out to let us know your thoughts!

Consider testing a strategy in paper trading to see if and how it works before trying it in a live brokerage account.

There are risks unique to automated trading algorithms that you should know about and plan for. You should setup a method or system of continuous monitoring or alerting to let you know if there is a mechanical failure, such as connectivity issues, power loss, a computer crash, or system quirk. You should also monitor for instances where your automated trading system experiences anomalies that could result in errant, missing, or duplicated orders.

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC, member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

Originally posted on Alpaca Forum.

--

--

Hitoshi Harada
Automation Generation

CTO/CoFounder @AlpacaHQ (YC W19) the API-first brokerage for algorithmic trading and developers (https://alpaca.markets)