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

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.

Manage Your Stocks from Google Spreadsheet Using API
You might think API trading is only for hard-core HFT programmers. That’s not true! Use a spreadsheet app with some… medium.com

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.

Project Jupyter
The Jupyter Notebook is a web-based interactive computing platform. The notebook combines live code, equations… jupyter.org

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.

Documentation | Alpaca
Welcome to Alpaca! Get familiar with Alpaca and explore the resources. In order to start using Alpaca Web API, you will… docs.alpaca.markets

Alpaca Forums
Powered by Discourse, best viewed with JavaScript enabled Providing technology services and brokerage services are not… forum.alpaca.markets

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

matplotlib/mpl_finance
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or… github.com

!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.

TensorFlow
Build and train ML models easily using intuitive high-level APIs like Keras with eager execution, which makes for… www.tensorflow.org

PyTorch
Pushing the state of the art in NLP and Multi-task learning. Using PyTorch’s flexibility to efficiently research new… pytorch.org

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
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or… github.com


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.

5 Likes

00%20PM

any help on screenshot? I’ve followed instructions and keep getting errors. thx.

Oh good catch. I guess the quote characters somehow got English quote characters. Could you try typing them manually?

1 Like

I’ve also corrected as many quotes as I find in the post above. Let me know if there is still something.

Thanks for help. Got it working.

Hi, thanks for the great article! I caught a few little things: there are still English quotes in the api.get_barset line. And the api.submit_order line needs a comma after ‘buy’. Otherwise awesome!! Thanks again.

1 Like

Thanks for the catch! Yes the input form replaced programming qutoe characters to English quote characters…

also pip install alpaca_trade_api has to be underscore

I’m getting an error right away when click on “New Python 3 notebook”

I am curious if there is anyway to implement the pipeline_live with google colab? pip installing both usually crashes my colab runtime. Seems to be issues with pandas, where zipline requires < 0.22 and colab requires >1.0.0

Hello. I followed the instructions in this article.

When selecting a New Notebook from “File” it doesn’t give the option for “New Python 3 Notebook”, it just says “New Notebook”.

When I run

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

with my Paper Trading API creds, I get a syntax error that reads:

File “”, line 1
import alpaca_trade_api as alpacaapi = alpaca.REST(‘xxxxxxxxxxx’, ‘xxxxxxxxxxxxxxx’, ‘https://paper-api.alpaca.markets’)
^
SyntaxError: invalid syntax

Is this because I’m not selecting the Python version? If so, how do I do that?

Thanks.

@Joseph Re your question Is this because I’m not selecting the Python version? Nope. Python 2 is no longer supported so all notebooks are now run on Python 3. There are a few differences between the two, but this code in specific runs fine in the default version.

More than likely the ‘syntax’ error you are getting is with the quote characters. They don’t copy and paste well. Manually delete and then re-type every single quote. That may fix it.

1 Like

How to get the order list into a table?

An order list (and many other lists such as assets, activities, etc) can easily be turned into a Pandas dataframe with the help of Python’s list comprehension and some Pandas magic. Most of the objects returned by the API methods include an attribute called _raw. Pandas recognizes this as a list (and not just a collection of attributes) and formats the result into a row of a dataframe. Iterate through all the objects and one gets a row for each object in the list. So, something like this will take a list of order objects and create a dataframe with one order per row. The columns will be the order attributes.

import pandas as pd

order_list = api.list_orders()
order_df = pd.DataFrame([order._raw for order in order_list])

The result looks like this (truncated here to fit on the page)

This same approach, as mentioned, can be used for most of the lists of objects returned by Alpaca APIs. It should be noted that some list results actually have a built in method .df which turns the result into a dataframe automagically. For example, the get_barset method returns a list of bars. Simply append .df and it becomes a dataframe.

bars_list = api.get_barset('BYND',timeframe='5Min',limit=1000,start='2020-01-06T14:35:00+00:00', end='2020-12-07T15:00:00+00:00' )
bars_list.df

This will return a dataframe like this


.df doesn’t work for all APIs but it’s worth a try. Otherwise, the list comprehension method above should do it.

Good luck.

1 Like

I am having the same issue as originally posted here. Followed the advise to change the single quotes. However, still getting syntax error on Google Colab.

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

SyntaxError: invalid syntax

Solved: It was really two lines of code that needed to be separated and then it worked. Looking back this was a rookie mistake.

I am trying to run this code in the example and keep getting this error

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

SyntaxError: invalid character in identifier

How can I fix it?

get_barset has been deprecated. As of March, you need to use get_bars instead.
GitHub - alpacahq/alpaca-trade-api-python: Python client for Alpaca’s trade API
Bear in mind that you now have to specify a start date/time.

1 Like

I am very new to programming and I am anxious to learn. Could you give me an example of the start date/time in a basic api for a daily chart on SPX?

If you are using Python, you could do something like this.

_symbol = 'SPY' #  Whichever ticker you want
_startDate = "2022-03-28" #  Monday last week
_timeFrame = TimeFrame.Day #  Daily bars

_bars = api.get_bars(symbol=_symbol, timeframe=_timeFrame, start=_startDate)
print(_bars)

This will will get all daily bars for SPY since Monday last week (28th March). Since the bars are calculated forwards (from the start date) you do not need to specify an end date. The default limit is 100, but you can specify this if you wish.