Trade Stocks in Your Browser Using Google Colab and Alpaca API

Google Colab allowing you to run Python Jupyter Notebook in the cloud. Introducing to utilize this environment for quant finance and algorithmic trading.

Trade Stocks in Your Browser Using Google Colab and Alpaca API

Alpaca makes it easier to trade stocks programmatically by offering a modern REST API. In fact, every day, we're seeing new people coming in and start trading stocks in a fully- or semi-automated fashion quickly, and we're still getting quite a bit of interest in our 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.

Manage Your Stocks from Google Spreadsheet Using API
This is the Dec 4th entry for Trading API Advent Calendar. Yesterday was a post with Yoshi’s futuristic view on automation. We still have slots available for this Advent Calendar so please reach out…

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 like Chrome or Firefox. Using Google Colab, not only can you start trading with Alpaca API instantly after getting your API key, but you also 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.

Project Jupyter
The Jupyter Notebook is a web-based interactive computing platform. The notebook combines live code, equations, narrative text, visualizations, interactive dashboards and other media.

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.

Welcome
This page will help you get started with Alpaca Docs. You’ll be up and running in a jiffy!
Alpaca Community Forum
Alpaca user forum for FAQ, feature requests, many discussions around Alpaca stock trading API

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-api

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 alpaca
api = alpaca.REST(‘YOUR_API_KEY_ID’, ‘YOUR_API_SECRET_KEY’, ‘https://paper-api.alpaca.markets’)

If no error is reported, you're 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.

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.submit_order(‘AAPL’, side='buy' qty=1, type=’market’, time_in_force=’gtc’)
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_bars(symbol=‘AAPL’, timeframe=‘1Day’, 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.

matplotlib/mpl-finance
This package is DEPRECATED, replaced by https://github.com/matplotlib/mplfinance - matplotlib/mpl-finance
!pip install mpl_finance

Then paste this snippet to draw candlestick chart.

import plotly.graph_objects as go

df =  client.get_bars(symbol= "AAPL", start= "2022-03-23",end= "2022-03-23",timeframe= "1Min").df

fig = go.Figure(data=[go.Candlestick(x=df.index,
                open=df['open'],
                high=df['high'],
                low=df['low'],
                close=df['close'])])

fig.show()
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.

TensorFlow
An end-to-end open source machine learning platform for everyone. Discover TensorFlow’s flexible ecosystem of tools, libraries and community resources.
PyTorch
An open source deep learning platform that provides a seamless path from research prototyping to production deployment.

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!

umitanuki/alpaca-colab
Example notebook for Alpaca API and Google Colab. Contribute to umitanuki/alpaca-colab development by creating an account on GitHub.

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.